import useSWR from 'swr';
import * as mockData from './mockData';

export interface ITableSchemaResponse {
  field: string;
  type: string;
  length: number;
}

export interface IService<T> {
  data: T | undefined;
  error: any;
}

// mock
const tableSchemaFetcher = async (key: {
  dataSource?: string;
  tableName?: string;
}): Promise<ITableSchemaResponse[]> => {
  const { dataSource, tableName } = key;
  if (!dataSource || !tableName) {
    return [];
  }
  // sleep 1
  await new Promise(resolve => setTimeout(resolve, 1));
  return mockData.tableSchema(dataSource);
};

// mock
const tableNamesFetcher = async (
  dataSource: string | undefined
): Promise<string[]> => {
  if (!dataSource) {
    return [];
  }
  // sleep 1
  await new Promise(resolve => setTimeout(resolve, 1));
  return mockData.tableNames(dataSource);
};

export const useTableSchema = (
  dataSource?: string,
  tableName?: string
): IService<ITableSchemaResponse[]> => {
  const { data, error } = useSWR(
    {
      dataSource,
      tableName
    },
    tableSchemaFetcher
  );
  return { data, error };
};

export const useTableNames = (dataSource?: string): IService<string[]> => {
  const { data, error } = useSWR(dataSource, tableNamesFetcher);
  return { data, error };
};
