import State = Phaser.State;
import {Pad} from '../input/Pad'

export class MenuScreen extends State {
    pad:Pad;
    menuItems:MenuItem[] = [];
    menuIndex = 0;

    music: Phaser.Sound;

    style = {font: "40px Arial", fill: "#ececec", align: "center"};
    styleActive = {font: "40px Arial", fill: "white", align: "center"};

    preload() {
        this.game.load.image('menu_bg', 'assets/images/menu_bg.png');
        this.game.load.audio('menu_music', 'assets/music/menu.ogg');
        this.game.load.audio('menu_select', 'assets/sounds/menu_select.ogg');
    }

    create() {
        // setup background
        this.game.stage.backgroundColor = '#201d1d';
        this.game.add.sprite(0, 0, 'menu_bg');

        this.music = this.game.add.audio('menu_music');
        this.music.play();

        var menuSelectSound = this.game.add.audio('menu_select');

        // setup controls
        this.game.input.gamepad.start();

        this.pad = new Pad(this.game.input.gamepad.pad1);

        this.pad.onUp = ()=> {
            this.menuIndex = Math.max(0, this.menuIndex - 1);
        };
        this.pad.onDown = ()=> {
            this.menuIndex = Math.min(this.menuItems.length - 1, this.menuIndex + 1);
        };
        this.pad.onAnyArrow = ()=> {
            this.updateActiveMenuItem();
        };
        this.pad.onThree = ()=> {
            var selectedMenuItem = this.menuItems[this.menuIndex];
            menuSelectSound.play();
            this.game.add.tween(selectedMenuItem.textElement)
                .to({x: this.game.world.width}, 300, Phaser.Easing.Bounce.Out, true)
                .onComplete.add(()=> {
                    if(selectedMenuItem.action)
                    {
                        selectedMenuItem.action();
                    }
                });
        };

        // setup menu items
        this.menuItems.push(new MenuItem(this, "Start", ()=> {
            this.game.state.start('actOne');
        }));

        this.positionMenuItems();

        this.updateActiveMenuItem();
    }

    shutdown(){
        this.music.stop();
    }

    positionMenuItems = () => {
        this.menuItems.reverse().forEach((item, index)=> {
            item.textElement.position.set(this.game.world.centerX - (item.textElement.width / 2), (this.game.world.height - 70) - index * 70);
        });
        this.menuItems.reverse();
    };

    updateActiveMenuItem = ()=> {
        this.menuItems.forEach((item, index)=> {
            item.textElement.setStyle(index === this.menuIndex ? this.styleActive : this.style);
        });
    };
}

class MenuItem {
    textElement:Phaser.Text;

    constructor(menu:MenuScreen, private caption:string, public action?:()=>void) {
        this.textElement = menu.game.add.text(0, 0, caption, menu.style);
    }
}