import * as electronRemote from '@electron/remote';
const electronConsole = electronRemote.getGlobal('console') as Console;
import Logger from '../../../../logger/logger';
const LOG = Logger.create(__filename, electronConsole);

import React, { FC, useEffect, useState } from 'react';

export interface TableProps<T> {
	header: JSX.Element;
	fetchData: () => Promise<T[]>;
	mapToRow: (data: T) => JSX.Element;
}

export default function Table<T>(props: TableProps<T>) {
	const { header, fetchData, mapToRow } = props;

	// TODO: Loading indicator + fetch failed indicator

	const [ dataRows, setDataRows ] = useState<JSX.Element[]>([]);
	const [ loading, setLoading ] = useState<boolean>(true);
	const [ fetchFailed, setFetchFailed ] = useState<boolean>(false);

	useEffect(() => {
		(async () => {
			setLoading(true);
			try {
				const data = await fetchData();
				setDataRows(data.map(mapToRow));
			} catch (e: unknown) {
				LOG.error('error fetching data for table', e);
				setFetchFailed(true);
			}
			setLoading(false);
		})();
	}, []);

	return (
		<table>
			<thead>{header}</thead>
			<tbody>{dataRows}</tbody>
		</table>
	)
}
