import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useEffect } from "react";
import useElectron from "../use-electron";
import useActiveDatasetManager from "../use-active-dataset-manager";
import LocalStorageDatasetManager from "udt-dataset-managers/dist/LocalStorageDatasetManager";
import templates from "../../components/StartingPage/templates";
import useToasts from "../use-toasts";
import toUDTCSV from "../../utils/to-udt-csv.js";
import useOpenFile from "../use-open-file";
export default (function () {
  var electron = useElectron();

  var _useToasts = useToasts(),
      addToast = _useToasts.addToast;

  var openFile = useOpenFile();

  var _useActiveDatasetMana = useActiveDatasetManager(),
      _useActiveDatasetMana2 = _slicedToArray(_useActiveDatasetMana, 2),
      dm = _useActiveDatasetMana2[0],
      setDatasetManager = _useActiveDatasetMana2[1];

  useEffect(function () {
    if (!electron) return;
    var ipcRenderer = electron.ipcRenderer,
        remote = electron.remote;

    var onOpenWelcomePage = function onOpenWelcomePage() {
      setDatasetManager(null);
    };

    var onNewFile = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(arg0) {
        var _ref2,
            templateName,
            newDM,
            _args = arguments;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _ref2 = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}, templateName = _ref2.templateName;
                newDM = new LocalStorageDatasetManager();
                _context.next = 4;
                return newDM.setDataset(templates.find(function (t) {
                  return t.name === templateName;
                }) || templates[0]);

              case 4:
                setDatasetManager(newDM);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function onNewFile(_x) {
        return _ref.apply(this, arguments);
      };
    }();

    function setFilePath() {
      return _setFilePath.apply(this, arguments);
    }

    function _setFilePath() {
      _setFilePath = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        var _yield$remote$dialog$2, cancelled, newFilePath, filePath;

        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return remote.dialog.showSaveDialog({
                  filters: [{
                    name: ".udt.json",
                    extensions: ["udt.json"]
                  }, {
                    name: ".udt.csv",
                    extensions: ["udt.csv"]
                  }]
                });

              case 2:
                _yield$remote$dialog$2 = _context3.sent;
                cancelled = _yield$remote$dialog$2.cancelled;
                newFilePath = _yield$remote$dialog$2.filePath;
                filePath = !newFilePath || newFilePath.endsWith(".json") || newFilePath.endsWith(".csv") ? newFilePath : "".concat(newFilePath, ".udt.json");

                if (!(cancelled || !filePath)) {
                  _context3.next = 9;
                  break;
                }

                addToast("Could not save");
                return _context3.abrupt("return");

              case 9:
                _context3.next = 11;
                return dm.setDatasetProperty("filePath", filePath);

              case 11:
                return _context3.abrupt("return", filePath);

              case 12:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));
      return _setFilePath.apply(this, arguments);
    }

    function saveFileAsync() {
      return _saveFileAsync.apply(this, arguments);
    }

    function _saveFileAsync() {
      _saveFileAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
        var _ref4,
            _ref4$saveAs,
            saveAs,
            filePath,
            ds,
            _args4 = arguments;

        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                _ref4 = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {}, _ref4$saveAs = _ref4.saveAs, saveAs = _ref4$saveAs === void 0 ? false : _ref4$saveAs;

                if (dm) {
                  _context4.next = 3;
                  break;
                }

                return _context4.abrupt("return");

              case 3:
                _context4.next = 5;
                return dm.getDatasetProperty("filePath");

              case 5:
                filePath = _context4.sent;

                if (!(!filePath || saveAs)) {
                  _context4.next = 10;
                  break;
                }

                _context4.next = 9;
                return setFilePath();

              case 9:
                filePath = _context4.sent;

              case 10:
                _context4.next = 12;
                return dm.getDataset();

              case 12:
                ds = _context4.sent;
                _context4.next = 15;
                return remote.require("fs").promises.writeFile(filePath, filePath.endsWith(".csv") ? toUDTCSV(ds) : JSON.stringify(ds, null, "  "));

              case 15:
                addToast("File Saved!");

              case 16:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }));
      return _saveFileAsync.apply(this, arguments);
    }

    var exportToCSV = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _yield$remote$dialog$, cancelled, filePath, ds;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (dm) {
                  _context2.next = 2;
                  break;
                }

                return _context2.abrupt("return");

              case 2:
                _context2.next = 4;
                return remote.dialog.showSaveDialog({
                  filters: [{
                    name: ".udt.csv",
                    extensions: ["udt.csv"]
                  }]
                });

              case 4:
                _yield$remote$dialog$ = _context2.sent;
                cancelled = _yield$remote$dialog$.cancelled;
                filePath = _yield$remote$dialog$.filePath;

                if (!cancelled) {
                  _context2.next = 9;
                  break;
                }

                return _context2.abrupt("return");

              case 9:
                _context2.next = 11;
                return dm.getDataset();

              case 11:
                ds = _context2.sent;
                filePath = !filePath || filePath.endsWith(".csv") ? filePath : "".concat(filePath, ".udt.csv");
                _context2.next = 15;
                return remote.require("fs").promises.writeFile(filePath, toUDTCSV(ds));

              case 15:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      return function exportToCSV() {
        return _ref3.apply(this, arguments);
      };
    }();

    var onOpenFileFromToolbar = function onOpenFileFromToolbar(e, file) {
      openFile(file);
    };

    var onSaveFile = function onSaveFile() {
      return saveFileAsync();
    };

    var onSaveFileAs = function onSaveFileAs() {
      return saveFileAsync({
        saveAs: true
      });
    };

    ipcRenderer.on("open-welcome-page", onOpenWelcomePage);
    ipcRenderer.on("new-file", onNewFile);
    ipcRenderer.on("open-file", onOpenFileFromToolbar);
    ipcRenderer.on("save-file", onSaveFile);
    ipcRenderer.on("save-file-as", onSaveFileAs);
    ipcRenderer.on("export-to-csv", exportToCSV);
    return function () {
      ipcRenderer.removeListener("open-welcome-page", onOpenWelcomePage);
      ipcRenderer.removeListener("new-file", onNewFile);
      ipcRenderer.removeListener("open-file", onOpenFileFromToolbar);
      ipcRenderer.removeListener("save-file", onSaveFile);
      ipcRenderer.removeListener("save-file-as", onSaveFileAs);
      ipcRenderer.removeListener("export-to-csv", exportToCSV);
    };
  }, [electron, dm, setDatasetManager, addToast, openFile]);
});