/*
 * InGameMenu
 *
 * Object for the ingame menu (contains sprite)
 */


export default class InGameMenu {

    constructor(state, choices) {

        this.state = state;

        this.choices = choices;
        
        this.isOpen = false;
        
        this.width = 100; // example;
        this.height = 100; // example;
        
        this.init();
    }
  
    init() {
        // create menu background
        this.bmd = this.state.game.add.bitmapData(this.width, this.height);

        this.bmd.ctx.beginPath(); 
        this.bmd.ctx.rect(0, 0, this.width, this.height);
        this.bmd.ctx.fillStyle = '#ffffff';
        this.bmd.ctx.fill();
    }
    
    open() {
        this.sprite = this.state.game.add.sprite(this.state.w / 2, this.state.h / 2, this.bmd);
        this.sprite.anchor.setTo(0.5, 0.5);

        // And a label to illustrate which menu item was chosen. (This is not necessary)
        this.choiceLabel = this.state.game.add.text(this.state.w / 2, this.state.h - 150, 'Click outside menu to continue', {
            font: '30px Arial',
            fill: '#fff'
        });
        this.choiceLabel.anchor.setTo(0.5, 0.5);
        
        this.isOpen = true;
    }
    
    close() {
        this.sprite.destroy();
        this.choiceLabel.destroy();
        this.isOpen = false;
    }

    getChoice(event) {
        // Calculate the corners of the menu
        var x1 = this.state.w/2 - 270/2, x2 = this.state.w/2 + 270/2,
            y1 = this.state.h/2 - 180/2, y2 = this.state.h/2 + 180/2;

        // TODO: paint entries
        // TODO: animate hover

        // Check if the click was inside the menu
        if(event.x > x1 && event.x < x2 && event.y > y1 && event.y < y2 ) {
            // The choicemap is an array that will help us see which item was clicked
            var choicemap = ['one', 'two', 'three', 'four', 'five', 'six'];

            // Get menu local coordinates for the click
            var x = event.x - x1,
                y = event.y - y1;

            // Calculate the choice
            var choice = Math.floor(x / 90) + 3 * Math.floor(y / 90);

            // Display the choice
            this.choiceLabel.text = 'You chose menu item: ' + choicemap[choice];
            
            return choicemap[choice];
            
        } else {
            // only do this if the menu is open and has to be closed
            if (this.isOpen) {
                // Remove the menu and the label
                this.close();

                // Unpause the game
                this.state.game.paused = false;
                
                return 'closed';
            }
        }

        return 'nuttin';
    }
}
