import { GameOverData } from "../gameoverscene/GameOverScene.js";
import { Level4 } from "../levels/Level4.js";
import { Level1 } from "../levels/Level1.js";
import { Level2 } from "../levels/Level2.js";
import { Level3 } from "../levels/Level3.js";
import { ScoreScene } from "../scorescene/ScoreScene.js";
import { framesPerStep } from "./Globals.js";
import { Level } from "./Level.js";


export class MainScene extends Phaser.Scene {
    
    levels: Level[] = [new Level1(this), new Level2(this), new Level3(this), new Level4(this)]

    currentLevel: Level;
    currentLevelIndex: number;


    constructor(){
        super({
            key: "MainScene"
        });
    }

    preload(){

        this.load.atlas('spritesheet', 'assets/graphics/spritesheet.png', 'assets/graphics/spritesheet.json');    

    }

    /**
     * After create has finished phaser calls ScoreScene.create. This in turn
     * calls onScoreSceneReady (see below).
     */
    create(){
        this.scene.launch("ScoreScene");
    }

    /**
     * This is called from scoreScene.create
     */
     onScoreSceneReady(){
        this.currentLevelIndex = 1;
        this.nextLevel();
    }


    /**
     * Each framesPerStep frames do a simulation-step:
     */
    frame: number = framesPerStep;

    update(time: number, delta: number){
       this.frame--;
       if(this.frame <= 0){
        this.frame = framesPerStep;
        if(this.currentLevel != null){
            this.currentLevel.simulateFallingBouldersAndGems();
        }
       }
    }


    getScoreScene(){
        return <ScoreScene>this.scene.get("ScoreScene");
    }

    getScoreBoard(){
        return this.getScoreScene().getScoreBoard();
    }

    /**
     * Starts next level
     */
    nextLevel(){
        if(this.currentLevel != null){
            this.currentLevel.destroyTiles();
        }

        this.currentLevelIndex = (this.currentLevelIndex + 1) % this.levels.length;
        this.currentLevel = this.levels[this.currentLevelIndex];
        this.currentLevel.setupTiles();
    }

    /**
     * Stops current Scene and starts GameOver-Scene.
     */
    gameOver(){
        // Pass level and points to GameOver-Scene:
        let data: GameOverData = {
            level: this.currentLevelIndex + 1,
            points: this.getScoreBoard().score
        }

        this.scene.stop("ScoreScene");
        this.scene.start("GameOverScene", data);

    }

}