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, createContext, useContext, useCallback } from "react";
import useMediaQuery from "@material-ui/core/useMediaQuery";
import LoginDrawer from "../LoginDrawer";
import CollaborativeDatasetManager from "udt-dataset-managers/dist/CollaborationServerDatasetManager";
import LocalStorageDatasetManager from "udt-dataset-managers/dist/LocalStorageDatasetManager";
import useEventCallback from "use-event-callback";
import { useAppConfig } from "../AppConfig";
import HeaderToolbar from "../HeaderToolbar";
import HeaderDrawer from "../HeaderDrawer";
import useOpenTemplate from "../../hooks/use-open-template";
import useActiveDatasetManager from "../../hooks/use-active-dataset-manager";
export var HeaderContext = createContext({
  recentItems: [],
  changeRecentItems: function changeRecentItems() {
    return null;
  },
  onClickTemplate: function onClickTemplate() {
    return null;
  },
  onClickHome: function onClickHome() {
    return null;
  },
  onOpenFile: function onOpenFile() {
    return null;
  },
  onOpenRecentItem: function onOpenRecentItem() {
    return null;
  },
  isDesktop: false,
  sessionBoxOpen: false,
  changeSessionBoxOpen: function changeSessionBoxOpen() {
    return null;
  },
  fileOpen: false,
  onDownload: function onDownload() {
    return null;
  },
  authConfig: null,
  onUserChange: function onUserChange() {
    return null;
  },
  user: null,
  logoutUser: function logoutUser() {
    return null;
  }
});
var emptyArray = [];
export default (function (_ref) {
  var _ref$additionalButton = _ref.additionalButtons,
      additionalButtons = _ref$additionalButton === void 0 ? emptyArray : _ref$additionalButton,
      title = _ref.title,
      currentTab = _ref.currentTab,
      onChangeTab = _ref.onChangeTab,
      _ref$tabs = _ref.tabs,
      tabs = _ref$tabs === void 0 ? emptyArray : _ref$tabs;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      drawerOpen = _useState2[0],
      changeDrawerOpen = _useState2[1];

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

  var _useAppConfig = useAppConfig(),
      fromConfig = _useAppConfig.fromConfig;

  var headerContext = useContext(HeaderContext);
  var openTemplate = useOpenTemplate();
  if (!headerContext.recentItems) headerContext.recentItems = [];
  var isSmall = useMediaQuery("(max-width: 800px)");
  var onOpenDrawer = useCallback(function () {
    return changeDrawerOpen(true);
  }, []);
  var onCloseDrawer = useCallback(function () {
    return changeDrawerOpen(false);
  }, []);

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

  var onCreateSession = useEventCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var previousUDTJSON, newDM;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!dm) {
              _context.next = 6;
              break;
            }

            _context.next = 3;
            return dm.getDataset();

          case 3:
            _context.t0 = _context.sent;
            _context.next = 7;
            break;

          case 6:
            _context.t0 = {
              interface: {},
              samples: []
            };

          case 7:
            previousUDTJSON = _context.t0;
            newDM = new CollaborativeDatasetManager({
              serverUrl: fromConfig("collaborationServer.url")
            });
            _context.prev = 9;
            _context.next = 12;
            return newDM.setDataset(previousUDTJSON);

          case 12:
            _context.next = 17;
            break;

          case 14:
            _context.prev = 14;
            _context.t1 = _context["catch"](9);
            console.log("Couldn't create collaborative session: ".concat(_context.t1.toString()));

          case 17:
            window.history.replaceState(null, null, "?s=".concat(encodeURIComponent(newDM.sessionId)));
            setActiveDatasetManager(newDM);

          case 19:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[9, 14]]);
  })));
  var onLeaveSession = useEventCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var ds, newDM;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (!dm) {
              _context2.next = 8;
              break;
            }

            _context2.next = 3;
            return dm.getDataset();

          case 3:
            ds = _context2.sent;
            newDM = new LocalStorageDatasetManager();
            _context2.next = 7;
            return newDM.setDataset(ds);

          case 7:
            setActiveDatasetManager(newDM);

          case 8:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  })));
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(HeaderToolbar, Object.assign({
    key: "headerToolbar",
    tabs: tabs,
    currentTab: currentTab,
    onChangeTab: onChangeTab,
    additionalButtons: additionalButtons,
    onOpenDrawer: onOpenDrawer,
    isSmall: isSmall
  }, headerContext, {
    inSession: dm && dm.type === "collaborative-session",
    onCreateSession: onCreateSession,
    onLeaveSession: onLeaveSession,
    changeLoginDrawerOpen: changeLoginDrawerOpen,
    title: title
  })), /*#__PURE__*/React.createElement(HeaderDrawer, {
    key: "headerDrawer",
    drawerOpen: drawerOpen,
    onCloseDrawer: onCloseDrawer,
    onClickHome: headerContext.onClickHome,
    onClickManagePlugins: headerContext.onClickManagePlugins,
    recentItems: headerContext.recentItems,
    changeRecentItems: headerContext.changeRecentItems,
    onOpenFile: headerContext.onOpenFile,
    onClickTemplate: openTemplate,
    onOpenRecentItem: headerContext.onOpenRecentItem
  }), /*#__PURE__*/React.createElement(LoginDrawer, {
    key: "loginDrawer",
    authConfig: headerContext.authConfig,
    loginDrawerOpen: loginDrawerOpen,
    onClose: function onClose() {
      return changeLoginDrawerOpen(false);
    },
    onUserChange: headerContext.onUserChange,
    logoutUser: headerContext.logoutUser
  }));
});