import { Board } from "../Board.js";
import { Button } from "../../libraries/components/Button.js";

export class MenuState {
    constructor(fsm) {
        this.stateMachine = fsm;
        this.boundMouseEvent = {};
    }

    init() {
        this.boundMouseEvent['mousedown'] = this.mouseDown.bind(this);
        this.boundMouseEvent['mousemove'] = this.mouseMove.bind(this);
        for(let key in this.boundMouseEvent) {
            window.addEventListener(key, this.boundMouseEvent[key]);
        }
        this.board = new Board();
        this.board.initDemo();
        this.playButton = new Button(0, 0, 160, 70, "Play");

        this.playButton.hoverFunction((ctx) => {
            ctx.fillStyle = "rgba(255,255,255,0.8)";
        });
        this.playButton.clickFunction(() => {
            this.stateMachine.transitionTo("levelselect");
        });

        this.deleteButton = new Button(0,0, 80, 20, "delete save", 
            {textFillStyle: "red", fontSize: 14, fontFamily: "Ariel", textStrokeStyle: null, backgroundFillStyle: null}
        );

        this.deleteButton.clickFunction(() => {
            if(confirm("Are you sure you want to reset your save data? This cannot be undone.")) {
                localStorage.removeItem('ballsort-playerdata');
                window.location.reload();
            }
        })
    }

    draw(ctx, scaledCanvas) {
        this.board.drawDemo(ctx,scaledCanvas);

        let canvasBounds = scaledCanvas.bounds;
        let center = canvasBounds.center;
        
        this.playButton.setPosition(center.x, center.y);
        this.playButton.draw(ctx,scaledCanvas);

        this.deleteButton.setPosition(center.x, canvasBounds.height - 20);
        this.deleteButton.draw(ctx, scaledCanvas);

        ctx.fillStyle = "white";
        ctx.strokeStyle = "black";
        ctx.font = "72px Luckiest Guy";
        ctx.textAlign = "center";
        ctx.lineWidth = 4;
        ctx.fillText(`Ballsort`, center.x, center.y - 82);
        ctx.strokeText(`Ballsort`, center.x, center.y - 82);        
    }

    update(delta) {

    }   

    mouseDown(event) {
        this.playButton.mouseDown(event);
        this.deleteButton.mouseDown(event);
    }

    mouseMove(event) {
        document.body.style.cursor = "default";
        this.playButton.mouseMove(event);
        this.deleteButton.mouseMove(event);
    }

    enter() {
        this.init();
    }
    leave() {
        for(let key in this.boundMouseEvent) {
            window.removeEventListener(key, this.boundMouseEvent[key]);
        }
    }
}