"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
require("core-js/modules/es.array.flat.js");
require("core-js/modules/es.array.unscopables.flat.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _PhaserGame = require("./game/PhaserGame");
require("./styles.css");
var _AppModule = _interopRequireDefault(require("./App.module.css"));
var _react = require("react");
var _connection = _interopRequireDefault(require("./connection"));
var _raftSubscriptionHelpers = require("./utils/raft-subscription-helpers");
var _raft = require("@robotical/webapp-types/dist-types/src/types/raft");
var _blockSelector = _interopRequireDefault(require("./block-selector"));
var _highScoreStore = require("./utils/high-score-store");
var _forward = require("./assets/blocks/forward.svg");
var _backward = require("./assets/blocks/backward.svg");
var _up = require("./assets/blocks/up.svg");
var _down = require("./assets/blocks/down.svg");
var _ontiltleft = require("./assets/blocks/ontiltleft.svg");
var _ontiltright = require("./assets/blocks/ontiltright.svg");
var _ontiltforward = require("./assets/blocks/ontiltforward.svg");
var _ontiltbackward = require("./assets/blocks/ontiltbackward.svg");
var _EventBus = require("./game/EventBus");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const repeat = (n, array) => {
  /* Repeats every element in the array until the array length = n */
  return Array(n).fill(array).flat().slice(0, n);
};
const posterItems = repeat(12, [{
  icon: _forward.ReactComponent,
  block: "right",
  execute: async () => true
}, {
  icon: _backward.ReactComponent,
  block: "left",
  execute: async () => true
}, {
  icon: _up.ReactComponent,
  block: "up",
  execute: async () => true
}, {
  icon: _down.ReactComponent,
  block: "down",
  execute: async () => true
}]);
const staticBlockItemsLeft = repeat(12, [{
  icon: _ontiltleft.ReactComponent,
  block: "ontiltleft",
  execute: async () => true
}]);
const staticBlockItemsRight = repeat(12, [{
  icon: _ontiltright.ReactComponent,
  block: "ontiltright",
  execute: async () => true
}]);
const staticBlockItemsForward = repeat(12, [{
  icon: _ontiltforward.ReactComponent,
  block: "ontiltup",
  execute: async () => true
}]);
const staticBlockItemsBackward = repeat(12, [{
  icon: _ontiltbackward.ReactComponent,
  block: "ontiltdown",
  execute: async () => true
}]);
function Maze() {
  const [gameContainerDimensions, setGameContainerDimensions] = (0, _react.useState)({
    width: "80vw",
    height: "60vh"
  });
  const [highScore, setHighScore] = (0, _react.useState)(0);
  const [score, setScore] = (0, _react.useState)(0);
  const phaserGameRef = (0, _react.useRef)(null);
  const [connectedCog, setConnectedCog] = (0, _react.useState)(null);
  const subHelper = (0, _react.useRef)(null);
  const [shouldShowGameFinished, setShouldShowGameFinished] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => {
    var _window$applicationMa;
    /* Checks if we are already connected to a cog */
    const selectedCog = (_window$applicationMa = window.applicationManager) === null || _window$applicationMa === void 0 ? void 0 : _window$applicationMa.getTheCurrentlySelectedDeviceOrFirstOfItsKind(_raft.RaftTypeE.COG);
    if (selectedCog) {
      setConnectedCog(selectedCog);
      subHelper.current = (0, _raftSubscriptionHelpers.raftDisconnectedSubscriptionHelper)(selectedCog);
      subHelper.current.subscribe(() => {
        var _subHelper$current;
        setConnectedCog(null);
        (_subHelper$current = subHelper.current) === null || _subHelper$current === void 0 || _subHelper$current.unsubscribe();
      });
    }
    return () => {
      var _subHelper$current2;
      (_subHelper$current2 = subHelper.current) === null || _subHelper$current2 === void 0 || _subHelper$current2.unsubscribe();
    };
  }, []);
  (0, _react.useEffect)(() => {
    /* Sets the score when the player goes through the exit or when star is collected */

    const scoreIncreaseHandler = scene => {
      setScore(scene.score);
      setHighScore((0, _highScoreStore.getHighScore)());
    };
    _EventBus.EventBus.on('player-went-through-exit', scoreIncreaseHandler);
    _EventBus.EventBus.on('player-collected-star', scoreIncreaseHandler);
    _EventBus.EventBus.on('game-finished', onGameFinishedHandler);
    return () => {
      _EventBus.EventBus.off('player-went-through-exit');
      _EventBus.EventBus.off('player-collected-star');
      _EventBus.EventBus.off('game-finished', onGameFinishedHandler);
    };
  }, []);
  const onGameFinishedHandler = scene => {
    console.log("Game finished");
    setShouldShowGameFinished(oldValue => !oldValue);
  };
  const handleConnect = () => {
    var _window$applicationMa2;
    (_window$applicationMa2 = window.applicationManager) === null || _window$applicationMa2 === void 0 || _window$applicationMa2.connectGenericCog(raft => {
      var _phaserGameRef$curren;
      (_phaserGameRef$curren = phaserGameRef.current) === null || _phaserGameRef$curren === void 0 || (_phaserGameRef$curren = _phaserGameRef$curren.scene) === null || _phaserGameRef$curren === void 0 || _phaserGameRef$curren.controls.registerCogEvents(raft);
      setConnectedCog(raft);
      subHelper.current = (0, _raftSubscriptionHelpers.raftDisconnectedSubscriptionHelper)(raft);
      subHelper.current.subscribe(() => {
        var _subHelper$current3;
        setConnectedCog(null);
        (_subHelper$current3 = subHelper.current) === null || _subHelper$current3 === void 0 || _subHelper$current3.unsubscribe();
      });
    });
  };
  const handleDisconnect = () => {
    if (connectedCog) {
      var _window$applicationMa3;
      (_window$applicationMa3 = window.applicationManager) === null || _window$applicationMa3 === void 0 || _window$applicationMa3.disconnectGeneric(connectedCog);
    }
  };
  (0, _react.useEffect)(() => {
    setHighScore((0, _highScoreStore.getHighScore)());
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: _AppModule.default.App,
    children: [shouldShowGameFinished && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: _AppModule.default.gameFinishedContainer,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
        className: _AppModule.default.gameFinishedText,
        children: "\uD83C\uDFC1 Game Finished \uD83C\uDFC1"
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: _AppModule.default.highScoreBoard,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h1", {
        children: "HIGH SCORE"
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: _AppModule.default.highScore,
        children: zeroPrepender(highScore, 4)
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: _AppModule.default.gameContainer,
      style: gameContainerDimensions,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: _AppModule.default.connectionButtonsContainer,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_connection.default, {
          connectedCog: connectedCog,
          setConnectedCog: setConnectedCog,
          handleDisconnect: handleDisconnect,
          handleConnect: handleConnect
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: _AppModule.default.blockSelectorContainerTop,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
          gameRef: phaserGameRef,
          staticBlockItems: staticBlockItemsLeft,
          posterItems: posterItems,
          staticBlock: "left"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
          gameRef: phaserGameRef,
          staticBlockItems: staticBlockItemsRight,
          posterItems: posterItems,
          staticBlock: "right"
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: _AppModule.default.blockSelectorContainerBottom,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
          gameRef: phaserGameRef,
          staticBlockItems: staticBlockItemsForward,
          posterItems: posterItems,
          staticBlock: "up"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
          gameRef: phaserGameRef,
          staticBlockItems: staticBlockItemsBackward,
          posterItems: posterItems,
          staticBlock: "down"
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: _AppModule.default.scoreBoard,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: _AppModule.default.score,
          children: zeroPrepender(score, 4)
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_PhaserGame.PhaserGame, {
        ref: phaserGameRef
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: _AppModule.default.playBtnContainer
    })]
  });
}
var _default = exports.default = Maze;
function zeroPrepender(num, size) {
  // helper function that prepends zeros to a number if it is less than a certain size
  // and also keeps only the first 'size' digits of the number if it is greater than 'size'
  let s = num + "";
  while (s.length < size) s = "0" + s;
  return s.slice(0, size);
}