import React, { useRef } from 'react';
import { Github } from '@db-man/github';
import { Button, Tooltip, Typography } from 'antd';
import * as constants from '../../constants';
import reloadDbsSchemaAsync from './helpers';
import EditableTable from './EditableTable';

// Use `Typography` so can apply dark theme to text
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const {
  Title
} = Typography;
const saveToFile = (data, filename) => {
  const blob = new Blob([data], {
    type: 'application/json'
  });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  link.click();
};

/**
 * To save online db tables schema in the local db, then pages could load faster
 */
const DbConnections = ({
  storage
}) => {
  const fileInputRef = useRef(null);
  const handleDbConnectionEnable = () => {
    const github = new Github({
      personalAccessToken: storage.get(constants.LS_KEY_GITHUB_PERSONAL_ACCESS_TOKEN) || '',
      owner: storage.get(constants.LS_KEY_GITHUB_OWNER) || '',
      repoName: storage.get(constants.LS_KEY_GITHUB_REPO_NAME) || ''
    });
    reloadDbsSchemaAsync(github).then(() => {});
  };
  const handleExport = () => {
    const jsonStrData = JSON.stringify({
      [constants.LS_KEY_DB_CONNECTIONS]: storage.get(constants.LS_KEY_DB_CONNECTIONS)
    });
    saveToFile(jsonStrData, 'DbManExportData.json');
  };
  const handleImport = () => {
    fileInputRef.current?.click();
  };
  const handleFileChange = event => {
    const file = event.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = e => {
      const jsonString = e.target?.result;
      const parsedData = JSON.parse(jsonString);
      storage.set(constants.LS_KEY_DB_CONNECTIONS, parsedData[constants.LS_KEY_DB_CONNECTIONS]);
      alert('Finish importing, refresh and enable one connection.');
    };
    reader.readAsText(file);
  };
  return /*#__PURE__*/_jsxs("div", {
    className: "dbm-db-connections",
    children: [/*#__PURE__*/_jsx(Title, {
      level: 2,
      children: "Database Connections"
    }), /*#__PURE__*/_jsx(EditableTable, {
      storage: storage,
      onEnable: handleDbConnectionEnable
    }), /*#__PURE__*/_jsx(Tooltip, {
      title: "Export the database connection configs to a JSON file.",
      children: /*#__PURE__*/_jsx(Button, {
        onClick: handleExport,
        children: "Export"
      })
    }), ' ', /*#__PURE__*/_jsx(Tooltip, {
      title: "Import a JSON file to replace all database connection configs",
      children: /*#__PURE__*/_jsx(Button, {
        onClick: handleImport,
        children: "Import"
      })
    }), /*#__PURE__*/_jsx("input", {
      ref: fileInputRef,
      style: {
        display: 'none'
      },
      type: "file",
      onChange: handleFileChange
    })]
  });
};
export default DbConnections;
//# sourceMappingURL=DbConnections.js.map