import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useState, useMemo, useEffect } from "react";
import useServer, { joinSession, convertToCollaborativeFile } from "./use-server";
import useFilesystem from "./use-filesystem";
import useLocalStorage from "./use-local-storage";
import { useToasts } from "../../components/Toasts";
import fromUDTCSV from "../from-udt-csv.js";
import useEventCallback from "use-event-callback";
import useFileTelemetry from "./use-file-telemetry";
import useAWSCognito from "./use-aws-cognito";
export default (function () {
  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      file = _useState2[0],
      setFile = _useState2[1];

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

  var _useFilesystem = useFilesystem(file, setFile),
      saveFile = _useFilesystem.saveFile;

  var _useLocalStorage = useLocalStorage(file, setFile),
      recentItems = _useLocalStorage.recentItems,
      changeRecentItems = _useLocalStorage.changeRecentItems;

  useServer(file, setFile); // Auth/Cloud

  useAWSCognito({
    file: file,
    setFile: setFile
  }); // Telemetry

  useFileTelemetry(file && file.content);
  var openFile = useEventCallback(function (fsFile) {
    var fileName = fsFile.name,
        filePath = fsFile.path;

    function handleLoadedFile(content) {
      try {
        var dataset;

        if (fileName.endsWith("csv")) {
          dataset = fromUDTCSV(content);
        } else {
          dataset = JSON.parse(content);
        } // TODO validate OHA and prompt to open anyway if invalid


        setFile({
          fileName: fileName,
          filePath: filePath,
          mode: filePath ? "filesystem" : "local-storage",
          content: dataset,
          id: filePath
        });
      } catch (e) {
        console.log(e.toString());
        addToast("Couldn't read file, see console for details", "error"); // addError(`Could not read file "${fsFile.name}"`)
      }
    }

    if (fsFile.content) {
      handleLoadedFile(fsFile.content);
    } else {
      var reader = new FileReader();

      reader.onload = function (e) {
        var content = e.target.result;
        handleLoadedFile(content);
      };

      reader.readAsText(fsFile);
    }
  });
  var openUrl = useEventCallback( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(url) {
      var sessionId, labelOnly, _yield$joinSession, state;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              sessionId = decodeURIComponent(url.match(/[?&]s=([^&]+)/)[1]);
              labelOnly = url.includes("mode=labelonly");

              if (sessionId) {
                _context.next = 4;
                break;
              }

              return _context.abrupt("return");

            case 4:
              _context.next = 6;
              return joinSession(sessionId);

            case 6:
              _yield$joinSession = _context.sent;
              state = _yield$joinSession.state;

              if (state) {
                _context.next = 10;
                break;
              }

              return _context.abrupt("return");

            case 10:
              window.history.replaceState({}, window.document.title, "/app/?s=".concat(encodeURIComponent(sessionId)).concat(labelOnly ? "&mode=labelonly" : ""));
              setFile({
                url: url,
                sessionId: sessionId,
                mode: "server",
                id: sessionId,
                content: state
              });

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

    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }());
  useEffect(function () {
    if (!file) return;
    if (file.mode === "server") return;
    window.history.replaceState({}, window.document.title, "/");
  }, [file]);
  useEffect(function () {
    if (window.location.search.match(/[?&]s=([a-zA-Z0-9]+)/)) {
      openUrl(window.location.href);
    }
  }, [openUrl]);
  var makeSession = useEventCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var newFile;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return convertToCollaborativeFile(file);

          case 2:
            newFile = _context2.sent;
            setFile(newFile);
            window.history.replaceState({}, window.document.title, "/app/?s=".concat(encodeURIComponent(newFile.sessionId)));

          case 5:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  })));
  return useMemo(function () {
    return {
      file: file,
      setFile: setFile,
      openFile: openFile,
      openUrl: openUrl,
      makeSession: makeSession,
      saveFile: saveFile,
      recentItems: recentItems,
      changeRecentItems: changeRecentItems
    };
  }, [file, setFile, openFile, saveFile, makeSession, recentItems, changeRecentItems, openUrl]);
});