/**
 * HUD to display score, number of gems to collect, lives, ...
 */
export class ScoreBoard {

    objects: Phaser.GameObjects.GameObject[] = [];
    background: Phaser.GameObjects.Rectangle;
    scoreText: Phaser.GameObjects.Text;
    gemText: Phaser.GameObjects.Text;
    camera: Phaser.Cameras.Scene2D.Camera;
    gem: Phaser.GameObjects.Sprite;
    doorTop: Phaser.GameObjects.Sprite;
    doorBottom: Phaser.GameObjects.Sprite;

    score: number = 0;
    gems: number = 0;

    constructor(private scene: Phaser.Scene){
        
        this.background = scene.add.rectangle(200 + 16, 5 + 8, 400, 30, 0x808080, 0.4);
        this.gem = scene.add.sprite(10, 16, "spritesheet1", "Boulder#4");
        this.gem.setScale(0.5);
        this.scoreText = scene.add.text(24, -4, "", {color: "#ffff00", fontSize: "32px", fontFamily: "sans-serif", stroke: "#000000", strokeThickness: 3})
        this.gemText = scene.add.text(224, -4, "", {color: "#00C000", fontSize: "32px", fontFamily: "sans-serif", stroke: "#000000", strokeThickness: 3})
        
        this.doorTop = scene.add.sprite(210, 12, "spritesheet1", "Boulder#10");
        this.doorTop.setScale(0.5);
        this.doorBottom = scene.add.sprite(210, 28, "spritesheet1", "Boulder#11");
        this.doorBottom.setScale(0.5);


        this.objects = [this.background, this.scoreText, this.gem, this.gemText];
        this.setScore(0);
        this.setGems(0);
    }

    openDoor(open: boolean){
        if(!open){
            this.doorTop.setFrame("Boulder#10");
            this.doorBottom.setFrame("Boulder#11");
        } else {
            this.doorTop.setFrame("Boulder#12");
            this.doorBottom.setFrame("Boulder#13");
        }
    }

    

    bringToFront(){
        this.objects.forEach((obj) => { this.scene.children.bringToTop(obj)});
    }
    
    destroy(){
        this.objects.forEach((obj) => { obj.destroy() });
    }

    setScore(score: number){
        this.score = score;
        this.scoreText.setText(this.fillWithNull(score, 6));
    }

    setGems(gems: number){
        this.gems = gems;
        this.gemText.setText(this.fillWithNull(gems, 2));
        this.openDoor(gems == 0);
    }

    addScore(points: number){
        this.setScore(this.score + points);
    }

    removeGems(gems: number){
        this.setGems(this.gems - gems);
        this.addScore(gems);
    }

    fillWithNull(n: number, numberOfChars: number): string {
        let text = "" + n;
        while(text.length < numberOfChars) text = "0" + text;
        return text;
    }

}