/* eslint-disable react/prop-types, react/destructuring-assignment, max-len, no-console, react/no-unused-class-component-methods */

import React, { useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { message } from 'antd';
import { GithubDb } from '@db-man/github';
import { getColumns, getPrimaryKey, getTablesByDbName } from '../dbs';
import * as constants from '../constants';
import PageContext from '../contexts/page';
import NavBar from '../components/NavBar';
import { useAppContext } from '../contexts/AppContext';
import { actionToComponentMapping } from '../pages';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const {
  Provider
} = PageContext;
export function TableList({
  dbName
}) {
  const {
    dbs,
    getTablesByDbName
  } = useAppContext();
  if (!dbs) return null;
  const tablesOfSelectedDb = getTablesByDbName(dbName);
  return /*#__PURE__*/_jsx("div", {
    children: tablesOfSelectedDb.map(({
      name: tName
    }) => /*#__PURE__*/_jsx("li", {
      children: /*#__PURE__*/_jsx(Link, {
        to: `/${dbName}/${tName}`,
        children: tName
      })
    }, tName))
  });
}
export function ActionList({
  dbName,
  tableName
}) {
  return /*#__PURE__*/_jsxs("div", {
    children: ["List of actions in table:", ['list', 'create'].map(action => /*#__PURE__*/_jsx("li", {
      children: /*#__PURE__*/_jsx(Link, {
        to: `/${dbName}/${tableName}/${action}`,
        children: action
      })
    }, action))]
  });
}

/**
 * To render list/create/update page for a real db table, e.g. `/iam/users.data.json`
 */
const DbTablePageWrapper = props => {
  const githubDbRef = useRef(new GithubDb({
    personalAccessToken: localStorage.getItem(constants.LS_KEY_GITHUB_PERSONAL_ACCESS_TOKEN) || '',
    repoPath: localStorage.getItem(constants.LS_KEY_GITHUB_REPO_PATH) || '',
    owner: localStorage.getItem(constants.LS_KEY_GITHUB_OWNER) || '',
    repoName: localStorage.getItem(constants.LS_KEY_GITHUB_REPO_NAME) || '',
    dbsSchema: localStorage.getItem(constants.LS_KEY_DBS_SCHEMA) || ''
  }));
  const {
    dbName,
    tableName,
    action
  } = props;
  useEffect(() => {
    getDbSchema();
    document.title = `${action} ${tableName}`;
  }, []);
  const columns = getColumns({
    dbName,
    tableName
  });
  const primaryKey = getPrimaryKey(columns);
  const pageInfo = () => {
    return {
      // e.g. ['split-table']
      appModes: localStorage.getItem(constants.LS_KEY_GITHUB_REPO_MODES) ? localStorage.getItem(constants.LS_KEY_GITHUB_REPO_MODES).split(',') : [],
      dbName: dbName || '',
      tableName: tableName || '',
      action: action || '',
      columns,
      primaryKey,
      tables: getTablesByDbName(dbName),
      githubDb: githubDbRef.current
    };
  };

  // get online and offline at the same time
  // then we only use offline data to render
  // compare the offline data with online data, if there is any diff, we show alert
  const getDbSchema = async () => {
    const offlineDbSchema = JSON.parse(localStorage.getItem(constants.LS_KEY_DBS_SCHEMA) || '{}')[props.dbName || ''];
    const onlineDbSchema = await githubDbRef.current.getDbTablesSchemaAsync(props.dbName);
    if (offlineDbSchema && onlineDbSchema) {
      const offlineDbSchemaStr = JSON.stringify(offlineDbSchema);
      const onlineDbSchemaStr = JSON.stringify(onlineDbSchema);
      if (offlineDbSchemaStr !== onlineDbSchemaStr) {
        console.warn('Offline and online schema are different!');
        console.warn('offlineDbSchema:', offlineDbSchema);
        console.warn('onlineDbSchema:', onlineDbSchema);
        message.warning( /*#__PURE__*/_jsxs("span", {
          children: ["Offline and online schema are different!", ' ', /*#__PURE__*/_jsx("a", {
            href: "/settings",
            children: "Go to Settings"
          })]
        }));
      }
    }
  };
  const errMsgs = [];
  if (!dbName) {
    errMsgs.push('dbName is undefined!');
  }
  if (primaryKey === null) {
    errMsgs.push('Primary key not found on table!');
  }
  if (columns.length === 0) {
    errMsgs.push('No columns found for this table!');
  }
  if (errMsgs.length > 0) {
    return /*#__PURE__*/_jsx("div", {
      className: "dbm-page-v2 err-msg",
      children: errMsgs.join(' ,')
    });
  }
  const PageComponent = actionToComponentMapping[action || ''];
  if (!PageComponent) {
    return /*#__PURE__*/_jsxs("div", {
      children: [/*#__PURE__*/_jsx("div", {
        children: "404 - PageComponent Not Found"
      }), /*#__PURE__*/_jsx("div", {
        children: `/${dbName}/${tableName}/${action}`
      })]
    });
  }
  return /*#__PURE__*/_jsx(Provider, {
    value: pageInfo(),
    children: /*#__PURE__*/_jsxs("div", {
      className: "dbm-page-v2",
      children: [/*#__PURE__*/_jsx(PageComponent, {
        dbName: dbName || '',
        tableName: tableName || ''
      }), /*#__PURE__*/_jsx(NavBar, {})]
    })
  });
};
export default DbTablePageWrapper;
//# sourceMappingURL=DbTablePageWrapper.js.map