import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { PhaserGame } from './game/PhaserGame';
import "./styles.css";
import styles from './App.module.css';
import { useEffect, useRef, useState } from 'react';
import { EventBus } from './game/EventBus';
import { ReactComponent as FlagsTarget } from './assets/flags-target-small.svg';
import { raftDisconnectedSubscriptionHelper } from './utils/raft-subscription-helpers';
import { RaftTypeE } from '@robotical/webapp-types/dist-types/src/types/raft';
import OverlayingTutorial from './overlaying-tutorial';
import WonOverlay from './WonOverlay';
import { ReactComponent as StarIcon } from './assets/flags.svg';
import { ReactComponent as OnTiltLeft } from "./assets/blocks/ontiltleft.svg";
import { ReactComponent as OnTiltRight } from "./assets/blocks/ontiltright.svg";
import { ReactComponent as ForwardIcon } from "./assets/blocks/forward.svg";
import { ReactComponent as BackwardIcon } from "./assets/blocks/backward.svg";
import { ReactComponent as NowhereIcon } from "./assets/blocks/nowhere.svg";
import BlockSelector2 from "./block-selector";
import { selectedBlockFromTutorialForLeft, selectedBlockFromTutorialForRight } from './utils/selected-blocks-from-tutorial';
import ShouldIStayOrShouldIGo from './ShouldIStayOrShouldIGo';
// const posterItemsLeft: PosterItem[] = [
//     { icon: ForwardIcon, block: "moveright", execute: async () => true },
// ];
// const posterItemsRight: PosterItem[] = [
//     { icon: BackwardIcon, block: "moveleft", execute: async () => true },
// ];
const staticBlockItemUp = { icon: OnTiltLeft, block: "ontiltleft", execute: async () => true };
const staticBlockItemDown = { icon: OnTiltRight, block: "ontiltright", execute: async () => true };
const repeat = (n, array) => {
    /* Repeats every element in the array until the array length = n */
    const repeated = [];
    for (let i = 0; i < n; i++) {
        repeated.push(array[i % array.length]);
    }
    return repeated;
};
const posterItems = repeat(12, [
    { icon: ForwardIcon, block: "moveright", execute: async () => true },
    { icon: NowhereIcon, block: "dontmove", execute: async () => true },
    { icon: BackwardIcon, 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] = useState({ width: "70vw", height: "80vh" });
    const [collectedFlags, setCollectedFlags] = useState(0);
    const [collectedFlagsText, setCollectedFlagsText] = useState("");
    const [isZooming, setIsZooming] = useState(false);
    const [isZoomingCenteredScore, setIsZoomingCenteredScore] = useState(false);
    const phaserGameRef = useRef(null);
    const [connectedCog, setConnectedCog] = useState(null);
    const [isWinningFlagVisible, setIsWinningFlagVisible] = useState(false);
    const [isSceneReady, setIsSceneReady] = useState(false);
    const [posterItemsLeftState, setPosterItemsLeftState] = useState([]);
    const [posterItemsRightState, setPosterItemsRightState] = useState([]);
    const [tutorialPhase, setTutorialPhase] = useState(1);
    const [shouldIStayOrShouldIGoVisible, setShouldIStayOrShouldIGoVisible] = useState(false);
    const subHelper = useRef(null);
    useEffect(() => {
        /* Checks if we are already connected to a cog */
        const selectedCog = window.applicationManager?.getTheCurrentlySelectedDeviceOrFirstOfItsKind(RaftTypeE.COG);
        if (selectedCog) {
            setConnectedCog(selectedCog);
            subHelper.current = raftDisconnectedSubscriptionHelper(selectedCog);
            subHelper.current.subscribe(() => {
                setConnectedCog(null);
                subHelper.current?.unsubscribe();
            });
        }
        return () => {
            subHelper.current?.unsubscribe();
        };
    }, []);
    const handleConnect = () => {
        window.applicationManager?.connectGenericCog((raft) => {
            setConnectedCog(raft);
            subHelper.current = raftDisconnectedSubscriptionHelper(raft);
            subHelper.current.subscribe(() => {
                setConnectedCog(null);
                subHelper.current?.unsubscribe();
            });
        });
    };
    const handleDisconnect = () => {
        if (connectedCog) {
            window.applicationManager?.disconnectGeneric(connectedCog);
        }
    };
    useEffect(() => {
        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.on('flags-collected', (scene_instance) => {
            setCollectedFlags(scene_instance.collectedFlags);
            setCollectedFlagsText(`+1=${scene_instance.collectedFlags}`);
        });
        EventBus.on('flags-lost', (scene_instance) => {
            setCollectedFlags(scene_instance.collectedFlags);
            setCollectedFlagsText(`-1=${scene_instance.collectedFlags}`);
        });
        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.on('die', () => {
            setCollectedFlags(0);
            setTutorialPhase(3);
            setPosterItemsLeftState([]);
            setPosterItemsRightState([]);
        });
        return () => {
            EventBus.removeListener('mountain-ready');
            EventBus.removeListener('die');
            EventBus.removeListener('flags-collected');
            EventBus.removeListener('flags-lost');
            EventBus.removeListener('target-achieved');
        };
    }, []);
    useEffect(() => {
        if (collectedFlags > 0) {
            setIsZooming(true);
            setTimeout(() => {
                setIsZooming(false);
            }, 300);
        }
    }, [collectedFlags]);
    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) {
            phaserGameRef.current?.scene?.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 = selectedBlockFromTutorialForLeft;
        const selectedBlockRight = 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 = () => {
        window.applicationManager.carouselNavigatorManager.getNavigator("games")?.navigate("/cog-shooter-game");
    };
    return (_jsxs("div", { className: styles.App, children: [isWinningFlagVisible && _jsx(WonOverlay, {}), shouldIStayOrShouldIGoVisible && _jsx(ShouldIStayOrShouldIGo, { keepPlaying: onKeepPlaying, goNext: onGoNext }), _jsx(OverlayingTutorial, { tutorialPhase: tutorialPhase, setTutorialPhase: setTutorialPhase, onTutorialFinished: onTutorialFinished }), _jsxs("div", { className: styles.gameContainer, style: gameContainerDimensions, children: [_jsx("div", { className: styles.blockSelectorContainer, children: isSceneReady && (_jsxs(_Fragment, { children: [!!posterItemsRightState.length && _jsx(BlockSelector2, { gameRef: phaserGameRef, staticBlock: "right", posterItems: posterItemsRightState, staticBlockItems: [staticBlockItemDown] }), !!posterItemsLeftState.length && _jsx(BlockSelector2, { gameRef: phaserGameRef, staticBlock: "left", staticBlockItems: [staticBlockItemUp], posterItems: posterItemsLeftState })] })) }), _jsxs("div", { className: styles.scoreBoard, children: [_jsx(StarIcon, { className: styles.starIcon }), _jsx("div", { className: `${styles.score} ${isZooming ? styles.zoom : ''}`, children: collectedFlags })] }), _jsx("div", { className: `${styles.centeredScore} ${isZoomingCenteredScore ? styles.flashScore : ''}`, children: collectedFlagsText }), _jsx("div", { className: styles.flagsTargetContainer, children: _jsx(FlagsTarget, { className: styles.flagsTargetIcon }) }), _jsx(PhaserGame, { ref: phaserGameRef })] })] }));
}
export 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);
}
