import { Component } from 'react';
import * as React from 'react';
import game from "../game/game"
import { AppState } from '../store';
import { connect } from "react-redux";
import { STEP_EXECUTION, ExecutionState } from '../store/executionState/types';
import { LevelInitializer } from '../game/levels';


interface LevelSceneProps {
    execState: ExecutionState,
    fast: boolean,
    step: () => void
    level: LevelInitializer
}

export class LevelScene extends Component<LevelSceneProps>  {
    mount: HTMLElement;
    retryTimer: number | null = null;
    retryCount: number = 0;

    componentDidMount() {
        window.addEventListener('resize', game.onWindowResize, false);
        this.mount.addEventListener('resize', game.onWindowResize, false);

        // Simplified initialization without visual corruption
        const initializeGame = () => {
            if (game.canStart()) {
                console.log('Player ready, starting game');
                game.start();
                game.onWindowResize();
                this.mount.appendChild(game.renderer.domElement);
            } else {
                // Single retry attempt after delay
                setTimeout(initializeGame, 100);
            }
        };
        
        initializeGame();
    }

    componentWillUnmount() {
        game.stop()
        if (this.retryTimer) {
            clearInterval(this.retryTimer);
            this.retryTimer = null;
        }
        if (this.mount.contains(game.renderer.domElement)) {
            this.mount.removeChild(game.renderer.domElement)
        }
    }

    componentDidUpdate(prevprops: LevelSceneProps) {
        if (prevprops.execState.instructionPtr !== this.props.execState.instructionPtr
            && this.props.execState.running) {
            let ins = this.props.execState.instruction
            if (ins) {
                game.player[ins]()
            }
        }
    }
    render() {
        let { running } = this.props.execState
        return (
            <div className="levelScene" ref={(mount: HTMLElement) => { this.mount = mount }} />
        )
    }
}

const mapStateToProps = (state: AppState, ownprops?) => {

    return { ...ownprops, execState: state.executionState }
}

const mapDispatchToProps = dispatch => {
    return {
        step: () => { dispatch({ type: STEP_EXECUTION }) }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(LevelScene)

