import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect } from "react";
import { HeaderContext } from "../Header";
import StartingPage from "../StartingPage";
import DatasetEditor from "../DatasetEditor";
import ErrorToasts from "../ErrorToasts";
import useErrors from "../../hooks/use-errors.js";
import useElectron from "../../hooks/use-electron.js";
import templates from "../StartingPage/templates";
import useEventCallback from "use-event-callback";
import { setIn } from "seamless-immutable";
import toUDTCSV from "../../utils/to-udt-csv.js";
import useFileHandler from "../../utils/file-handlers";

var randomId = function randomId() {
  return Math.random().toString().split(".")[1];
};

export default (function () {
  var _file$content, _file$content2, _file$content2$interf;

  var _useFileHandler = useFileHandler(),
      file = _useFileHandler.file,
      setFile = _useFileHandler.setFile,
      openFile = _useFileHandler.openFile,
      openUrl = _useFileHandler.openUrl,
      makeSession = _useFileHandler.makeSession,
      saveFile = _useFileHandler.saveFile,
      recentItems = _useFileHandler.recentItems;

  var _useState = useState("complete"),
      _useState2 = _slicedToArray(_useState, 2),
      selectedBrush = _useState2[0],
      setSelectedBrush = _useState2[1];

  var _useErrors = useErrors(),
      _useErrors2 = _slicedToArray(_useErrors, 1),
      errors = _useErrors2[0];

  var _useElectron = useElectron(),
      remote = _useElectron.remote,
      ipcRenderer = _useElectron.ipcRenderer;

  var onCreateTemplate = useEventCallback(function (template) {
    setFile({
      fileName: "unnamed",
      content: template.dataset,
      id: randomId(),
      mode: "filesystem"
    });
  });
  var openRecentItem = useEventCallback(function (item) {
    return setFile(item);
  });
  var onClickHome = useEventCallback(function () {
    return setFile(null);
  });
  useEffect(function () {
    var onOpenWelcomePage = function onOpenWelcomePage() {
      return setFile(null);
    };

    var onNewFile = function onNewFile(arg0) {
      var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          templateName = _ref.templateName;

      onCreateTemplate(templates.find(function (t) {
        return t.name === templateName;
      }) || templates[0]);
    };

    var saveFileAs = function saveFileAs() {
      return saveFile({
        saveAs: true
      });
    };

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

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (file) {
                  _context.next = 2;
                  break;
                }

                return _context.abrupt("return");

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

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

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

                return _context.abrupt("return");

              case 9:
                filePath = !filePath || filePath.endsWith(".csv") ? filePath : "".concat(filePath, ".udt.csv");
                _context.next = 12;
                return remote.require("fs").promises.writeFile(filePath, toUDTCSV(file.content));

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

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

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

    ipcRenderer.on("open-welcome-page", onOpenWelcomePage);
    ipcRenderer.on("new-file", onNewFile);
    ipcRenderer.on("open-file", onOpenFileFromToolbar);
    ipcRenderer.on("save-file", saveFile);
    ipcRenderer.on("save-file-as", saveFileAs);
    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", saveFile);
      ipcRenderer.removeListener("save-file-as", saveFileAs);
      ipcRenderer.removeListener("export-to-csv", exportToCSV);
    };
  }, [file, setFile, ipcRenderer, openFile, onCreateTemplate, remote, saveFile]);
  var inSession = file && file.mode === "server";

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      sessionBoxOpen = _useState4[0],
      changeSessionBoxOpen = _useState4[1];

  var onJoinSession = useEventCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(sessionName) {
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return openUrl(sessionName);

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

    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }());
  var onLeaveSession = useEventCallback(function () {
    return setFile(_objectSpread(_objectSpread({}, file), {}, {
      mode: "local-storage",
      fileName: file.fileName || "copy_of_".concat(file.id)
    }));
  });
  var collaborateError = ((file === null || file === void 0 ? void 0 : (_file$content = file.content) === null || _file$content === void 0 ? void 0 : _file$content.samples) || []).some(function (sample) {
    return [sample.imageUrl, sample.videoUrl, sample.pdfUrl].filter(Boolean).map(function (a) {
      return a.includes("file://");
    }).some(Boolean);
  }) ? "Some URLs (links) in this file are connected to files on your computer. Use the Samples > Transform > Transform Files to Web URLs to upload these files, then collaboration will be available." : null;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(HeaderContext.Provider, {
    value: {
      recentItems: recentItems,
      onClickTemplate: onCreateTemplate,
      onClickHome: onClickHome,
      title: file ? file.mode !== "server" ? file.fileName : file.url : "unnamed",
      fileOpen: Boolean(file),
      interfaceType: file === null || file === void 0 ? void 0 : (_file$content2 = file.content) === null || _file$content2 === void 0 ? void 0 : (_file$content2$interf = _file$content2.interface) === null || _file$content2$interf === void 0 ? void 0 : _file$content2$interf.type,
      onOpenRecentItem: openRecentItem,
      isDesktop: true,
      onOpenFile: openFile,
      selectedBrush: selectedBrush,
      onChangeSelectedBrush: setSelectedBrush,
      // collaboration session
      inSession: inSession,
      sessionBoxOpen: sessionBoxOpen,
      changeSessionBoxOpen: changeSessionBoxOpen,
      collaborateError: collaborateError,
      onJoinSession: onJoinSession,
      onLeaveSession: onLeaveSession,
      onCreateSession: makeSession,
      isWelcomePage: !file
    }
  }, !file ? /*#__PURE__*/React.createElement(StartingPage, {
    showDownloadLink: false,
    onFileDrop: openFile,
    onOpenTemplate: onCreateTemplate,
    recentItems: recentItems,
    onOpenRecentItem: openRecentItem
  }) : /*#__PURE__*/React.createElement(DatasetEditor, Object.assign({
    key: file.id
  }, file, {
    inSession: inSession,
    selectedBrush: selectedBrush,
    dataset: file.content,
    onChangeFileName: function onChangeFileName(newName) {
      setFile(setIn(file, ["fileName"], newName));
    },
    onChangeDataset: function onChangeDataset(newOHA) {
      setFile(setIn(file, ["content"], newOHA));
    }
  }))), /*#__PURE__*/React.createElement(ErrorToasts, {
    errors: errors
  }));
});