"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 _EventBus = require("./game/EventBus");
var _flagsTargetSmall = require("./assets/flags-target-small.svg");
var _raftSubscriptionHelpers = require("./utils/raft-subscription-helpers");
var _raft = require("@robotical/webapp-types/dist-types/src/types/raft");
var _overlayingTutorial = _interopRequireDefault(require("./overlaying-tutorial"));
var _WonOverlay = _interopRequireDefault(require("./WonOverlay"));
var _flags = require("./assets/flags.svg");
var _ontiltleft = require("./assets/blocks/ontiltleft.svg");
var _ontiltright = require("./assets/blocks/ontiltright.svg");
var _forward = require("./assets/blocks/forward.svg");
var _backward = require("./assets/blocks/backward.svg");
var _nowhere = require("./assets/blocks/nowhere.svg");
var _blockSelector = _interopRequireDefault(require("./block-selector"));
var _selectedBlocksFromTutorial = require("./utils/selected-blocks-from-tutorial");
var _ShouldIStayOrShouldIGo = _interopRequireDefault(require("./ShouldIStayOrShouldIGo"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
// const posterItemsLeft: PosterItem[] = [
//     { icon: ForwardIcon, block: "moveright", execute: async () => true },
// ];
// const posterItemsRight: PosterItem[] = [
//     { icon: BackwardIcon, block: "moveleft", execute: async () => true },
// ];
const staticBlockItemUp = {
  icon: _ontiltleft.ReactComponent,
  block: "ontiltleft",
  execute: async () => true
};
const staticBlockItemDown = {
  icon: _ontiltright.ReactComponent,
  block: "ontiltright",
  execute: async () => true
};
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: "moveright",
  execute: async () => true
}, {
  icon: _nowhere.ReactComponent,
  block: "dontmove",
  execute: async () => true
}, {
  icon: _backward.ReactComponent,
  block: "moveleft",
  execute: async () => true
}]);

// const staticBlockItemsUp: PosterItem[] = repeat(12, [
//     { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true },
// ]);

// const staticBlockItemsDown: PosterItem[] = repeat(12, [
//     { icon: OnTiltRight, block: "ontiltright", execute: async () => true },
// ]);

function Skiing() {
  const [gameContainerDimensions, setGameContainerDimensions] = (0, _react.useState)({
    width: "70vw",
    height: "80vh"
  });
  const [collectedFlags, setCollectedFlags] = (0, _react.useState)(0);
  const [collectedFlagsText, setCollectedFlagsText] = (0, _react.useState)("");
  const [isZooming, setIsZooming] = (0, _react.useState)(false);
  const [isZoomingCenteredScore, setIsZoomingCenteredScore] = (0, _react.useState)(false);
  const phaserGameRef = (0, _react.useRef)(null);
  const [connectedCog, setConnectedCog] = (0, _react.useState)(null);
  const [isWinningFlagVisible, setIsWinningFlagVisible] = (0, _react.useState)(false);
  const [isSceneReady, setIsSceneReady] = (0, _react.useState)(false);
  const [posterItemsLeftState, setPosterItemsLeftState] = (0, _react.useState)([]);
  const [posterItemsRightState, setPosterItemsRightState] = (0, _react.useState)([]);
  const [tutorialPhase, setTutorialPhase] = (0, _react.useState)(1);
  const [shouldIStayOrShouldIGoVisible, setShouldIStayOrShouldIGoVisible] = (0, _react.useState)(false);
  const subHelper = (0, _react.useRef)(null);
  (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();
    };
  }, []);
  const handleConnect = () => {
    var _window$applicationMa2;
    (_window$applicationMa2 = window.applicationManager) === null || _window$applicationMa2 === void 0 || _window$applicationMa2.connectGenericCog(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)(() => {
    _EventBus.EventBus.on('mountain-ready', mountain => {
      const mountainHeightScaled = mountain.height * mountain.scaleFactors.height;
      const mountainWidthScaled = mountain.width * mountain.scaleFactors.width;
      setGameContainerDimensions({
        width: mountainWidthScaled + "px",
        height: mountainHeightScaled + "px"
      });
      setIsSceneReady(true);
    });
    _EventBus.EventBus.on('flags-collected', scene_instance => {
      setCollectedFlags(scene_instance.collectedFlags);
      setCollectedFlagsText("+1=".concat(scene_instance.collectedFlags));
    });
    _EventBus.EventBus.on('flags-lost', scene_instance => {
      setCollectedFlags(scene_instance.collectedFlags);
      setCollectedFlagsText("-1=".concat(scene_instance.collectedFlags));
    });
    _EventBus.EventBus.on('target-achieved', () => {
      if (!phaserGameRef.current) return;
      if (!phaserGameRef.current.scene) return;
      setIsWinningFlagVisible(true);
      setTimeout(() => {
        setIsWinningFlagVisible(false);
        setShouldIStayOrShouldIGoVisible(true);
        // window.applicationManager.carouselNavigatorManager.getNavigator("games")?.setIsVisible(true);
        // window.applicationManager.carouselNavigatorManager.getNavigator("games")?.setHighlightedItem("/maze");
      }, 2000);
    });
    _EventBus.EventBus.on('die', () => {
      setCollectedFlags(0);
      setTutorialPhase(3);
      setPosterItemsLeftState([]);
      setPosterItemsRightState([]);
    });
    return () => {
      _EventBus.EventBus.removeListener('mountain-ready');
      _EventBus.EventBus.removeListener('die');
      _EventBus.EventBus.removeListener('flags-collected');
      _EventBus.EventBus.removeListener('flags-lost');
      _EventBus.EventBus.removeListener('target-achieved');
    };
  }, []);
  (0, _react.useEffect)(() => {
    if (collectedFlags > 0) {
      setIsZooming(true);
      setTimeout(() => {
        setIsZooming(false);
      }, 300);
    }
  }, [collectedFlags]);
  (0, _react.useEffect)(() => {
    if (collectedFlags > 0) {
      setIsZoomingCenteredScore(true);
      setTimeout(() => {
        setIsZoomingCenteredScore(false);
      }, 1500);
    }
  }, [collectedFlags]);
  const onPlayBtnClick = () => {
    // if cog is connected, start the game, otherwise connect a cog
    if (connectedCog) {
      var _phaserGameRef$curren;
      (_phaserGameRef$curren = phaserGameRef.current) === null || _phaserGameRef$curren === void 0 || (_phaserGameRef$curren = _phaserGameRef$curren.scene) === null || _phaserGameRef$curren === void 0 || _phaserGameRef$curren.handleGameStart();
    } else {
      handleConnect();
    }
  };
  const onTutorialFinished = () => {
    // when the tutorial is finished, we get the selected blocks from the programming phase
    // and we push them to the poster items

    // const selectedBlockLeft = selectedBlockFromTutorialForLeft;
    // const selectedBlockRight = selectedBlockFromTutorialForRight;
    // if (selectedBlockLeft) {
    //     setPosterItemsLeftState([selectedBlockLeft]);
    // }
    // if (selectedBlockRight) {
    //     setPosterItemsRightState([selectedBlockRight]);
    // }

    const selectedBlockLeft = _selectedBlocksFromTutorial.selectedBlockFromTutorialForLeft;
    const selectedBlockRight = _selectedBlocksFromTutorial.selectedBlockFromTutorialForRight;
    if (selectedBlockLeft) {
      const index = posterItems.findIndex(item => item.block === selectedBlockLeft.block);
      if (index !== -1) {
        const selectedBlock = posterItems[index];
        posterItems.splice(index, 1);
        posterItems.unshift(selectedBlock);
        setPosterItemsLeftState([...posterItems]);
      }
    }
    if (selectedBlockRight) {
      const index = posterItems.findIndex(item => item.block === selectedBlockRight.block);
      if (index !== -1) {
        const selectedBlock = posterItems[index];
        posterItems.splice(index, 1);
        posterItems.unshift(selectedBlock);
        setPosterItemsRightState([...posterItems]);
      }
    }
    setTutorialPhase(undefined);
  };
  const onKeepPlaying = () => {
    setShouldIStayOrShouldIGoVisible(false);
    setCollectedFlags(0);
    setCollectedFlagsText("");
    setTutorialPhase(3);
    setPosterItemsLeftState([]);
    setPosterItemsRightState([]);
  };
  const onGoNext = () => {
    var _window$applicationMa4;
    (_window$applicationMa4 = window.applicationManager.carouselNavigatorManager.getNavigator("games")) === null || _window$applicationMa4 === void 0 || _window$applicationMa4.navigate("/cog-shooter-game");
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: _AppModule.default.App,
    children: [isWinningFlagVisible && /*#__PURE__*/(0, _jsxRuntime.jsx)(_WonOverlay.default, {}), shouldIStayOrShouldIGoVisible && /*#__PURE__*/(0, _jsxRuntime.jsx)(_ShouldIStayOrShouldIGo.default, {
      keepPlaying: onKeepPlaying,
      goNext: onGoNext
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_overlayingTutorial.default, {
      tutorialPhase: tutorialPhase,
      setTutorialPhase: setTutorialPhase,
      onTutorialFinished: onTutorialFinished
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: _AppModule.default.gameContainer,
      style: gameContainerDimensions,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: _AppModule.default.blockSelectorContainer,
        children: isSceneReady && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [!!posterItemsRightState.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
            gameRef: phaserGameRef,
            staticBlock: "right",
            posterItems: posterItemsRightState,
            staticBlockItems: [staticBlockItemDown]
          }), !!posterItemsLeftState.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockSelector.default, {
            gameRef: phaserGameRef,
            staticBlock: "left",
            staticBlockItems: [staticBlockItemUp],
            posterItems: posterItemsLeftState
          })]
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: _AppModule.default.scoreBoard,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_flags.ReactComponent, {
          className: _AppModule.default.starIcon
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "".concat(_AppModule.default.score, " ").concat(isZooming ? _AppModule.default.zoom : ''),
          children: collectedFlags
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "".concat(_AppModule.default.centeredScore, " ").concat(isZoomingCenteredScore ? _AppModule.default.flashScore : ''),
        children: collectedFlagsText
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: _AppModule.default.flagsTargetContainer,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_flagsTargetSmall.ReactComponent, {
          className: _AppModule.default.flagsTargetIcon
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_PhaserGame.PhaserGame, {
        ref: phaserGameRef
      })]
    })]
  });
}
var _default = exports.default = Skiing;
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);
}