import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import { useEffect } from "react";
import CollaborationHandler from "./handler.js";
import { setIn } from "seamless-immutable";
var serverUrl = window.localStorage.CUSTOM_COLLABORATION_SERVER || "https://udt-collaboration-server.now.sh"; // We use a global singleton to manage the collaboration state machine

var collab = new CollaborationHandler({
  serverUrl: serverUrl
});
export var convertToCollaborativeFile = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file) {
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return collab.createSession(file.content);

          case 2:
            return _context.abrupt("return", {
              fileName: file.fileName,
              id: file.id,
              sessionId: collab.sessionId,
              url: "".concat(window.location.origin, "/app/?s=").concat(collab.sessionId),
              content: file.content,
              mode: "server"
            });

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

  return function convertToCollaborativeFile(_x) {
    return _ref.apply(this, arguments);
  };
}();
export var joinSession = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(sessionId) {
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return collab.joinSession(sessionId);

          case 2:
            return _context2.abrupt("return", {
              state: collab.state,
              version: collab.version
            });

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

  return function joinSession(_x2) {
    return _ref2.apply(this, arguments);
  };
}();
export default (function (file, changeFile) {
  // const { addToast } = useToasts()
  var userName = window.localStorage.userName;
  useEffect(function () {
    if (userName && !userName.includes("anonymous")) {
      try {
        collab.userName = JSON.parse(window.localStorage.userName);
      } catch (e) {}
    }
  }, [userName]);
  useEffect(function () {
    if (!file || file.mode !== "server") return;
    if (file.sessionId !== collab.sessionId) return;

    var checkForLatestPatch = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        var applyResult;
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return collab.applyLatestPatches();

              case 2:
                applyResult = _context3.sent;

                if (applyResult) {
                  // TODO apply in a smart, immutable way
                  changeFile(setIn(file, ["content"], collab.state));
                }

                if (timeout) {
                  _context3.next = 6;
                  break;
                }

                return _context3.abrupt("return");

              case 6:
                timeout = setTimeout(checkForLatestPatch, 500);

              case 7:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

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

    var timeout = setTimeout(checkForLatestPatch, 500);
    return function () {
      clearTimeout(timeout);
      timeout = null;
    };
  }, [file, changeFile]); // Update the Server State by Sending Patches

  useEffect(function () {
    if (!file || file.mode !== "server") return;
    collab.sendPatchIfChanged(file.content);
  }, [file]);
});