import React from 'react';
import { ReactWidget } from '@jupyterlab/apputils';
import { Widget } from '@lumino/widgets';
import DataTable from './DataTable';
import {
  fetchTableContent,
  fetchTableSchema,
  IDatasourceItem,
  ITableData
} from './api/datasource';

class DataTableWidget extends ReactWidget {
  constructor(
    datasource: IDatasourceItem,
    tableName: string,
    action: 'schema' | 'content',
    options?: Widget.IOptions
  ) {
    super(options);
    void this._requestData(datasource, tableName, action);
  }

  private _requestData = async (
    datasource: IDatasourceItem,
    tableName: string,
    action: 'schema' | 'content'
  ) => {
    const res =
      action === 'content'
        ? await fetchTableContent(datasource, tableName)
        : await fetchTableSchema(datasource, tableName);
    if (res === 'error') {
      this._err = res;
    } else {
      this._data = res;
    }
    this.update();
  };

  render(): JSX.Element {
    if (this._err) {
      return <div>Error</div>;
    } else if (!this._data) {
      return <div>Loading ...</div>;
    } else {
      return <DataTable data={this._data} />;
    }
  }

  private _data: ITableData | null = null;
  private _err: any;
}

export default DataTableWidget;
