/*
 * Game state
 * ==========
 *
 * A sample Game state, displaying the Phaser logo.
 */

import Logo from '../objects/Logo';
import LeLevel from '../objects/LeLevel';
import Selector from '../objects/Selector';
import InGameMenu from '../objects/InGameMenu';

var gamesettings = {
    animation: {
        speed:      150,
        easing:     Phaser.Easing.Linear.None
    }
};

var gamestate = {
    debug: false,
    status: 'playing',
    level: 0,
    cursors: {
        leftdown: false,
        leftacted: false,

        rightdown: false,
        rightacted: false,

        updown: false,
        upacted: false,

        downdown: false,
        downacted: false
    },
    keys: {
        spacedown: false,
        spcaeacted: false,

        adown: false,
        aacted: false,

        sdown: false,
        sacted: false,

        rdown: false,
        racted: false

    },
    selector: null
    // {
    //     sprite: null,
    //     x: 0,
    //     y: 0
    // }
};

var leveldata = {
    0: {
        color: '#666666',
        title: 'Don\'t panic'
    },
    1: {
        color: '#555555',
        title: 'Easy enough'
    },
    2: {
        color: '#779594',
        title: 'Where did that come from'
    },
    3: {
        color: '#666666',
        title: 'Getting interesting'
    },
    4: {
        color: '#555555',
        title: 'Notre Dame'
    },
    5: {
        color: '#779594',
        title: 'Stone Flower'
    },
    6: {
        color: '#666666',
        title: 'Starburst'
    },
    7: {
        color: '#779594',
        title: 'Where to go'
    },
    8: {
        color: '#666666',
        title: 'Borg borg borg, ... booooooooooorg'
    },
    9: {
        color: '#292D3A',
        title: 'Ducky Duck'
    },
    10: {
        color: '#999999',
        title: 'Penultimo'
    },
    11: {
        color: '#999999',
        title: 'Megaship'
    }
};

export default class Game extends Phaser.State {

    preload () {
        // console.log(gamestate);
        this.level = new LeLevel(this, 'level' + gamestate.level);
        // this.level = new LeLevel(this, 'puzzler-leveltest');
        this.level.preload();
        this.game.stage.backgroundColor = '#292D3A';
        this.game.stage.backgroundColor = leveldata[gamestate.level].color;
    }

    create() {

        ga('send', 'event', 'LD#35', 'level started', this.level);
        
        this.gamestate = gamestate;
        this.gamesettings = gamesettings;

        this.w = 800;
        this.h = 600;

        this.isAnimating = false;
        this.keyQueue = [];
        
        this.menukey = false;

        // this.pausemenu = new InGameMenu(this, ['test']);

        this.cursors = this.input.keyboard.createCursorKeys();

        const {centerX: x, centerY: y} = this.world;
        
        // DEMO LOGO
        // ---------------------
        
        // this.add.existing(new Logo(this.game, x, y));

        // ---------------------

    /*
     Code for the pause menu
     as per http://phaser.io/examples/v2/misc/pause-menu
     */
        // Create a label to use as a button
        // var pause_label = this.game.add.text(this.w - 100, 20, 'Pause', { font: '24px Arial', fill: '#fff' });
        // pause_label.inputEnabled = true;
        // pause_label.events.onInputUp.add(function () {
        //
        //     // When the paus button is pressed, we pause the game
        //     this.game.paused = true;
        //     this.pausemenu.open();
        //
        // }, this);

        this.input.onDown.add(this.onDown, this);

        
    // init 'ESC to menu'
    // --------------------------
        var that = this;
        window.onkeydown = function(event) {
            var thet = that;
            if (event.keyCode === Phaser.Keyboard.ESC) {
                thet.game.paused = false;
                thet.state.start('Menu'); 
            }
        };
    // --------------------------
        
        
        
    // LEVEL
    // =========================

        this.level.init( -1, -1);

    // =========================



    // SELECTOR
    // =========================

        this._controlsgroup = this.game.add.group();
        gamestate.selector = new Selector(this);

    // =========================


    // TITLE
    // =========================
        var style_press = {font: 'italic 23px Arial', fill: '#cccccc', align: 'center'};
        this.title = this.game.add.text(20, 10, "Level " + gamestate.level + ": " + leveldata[gamestate.level].title, style_press);



    // SOUNDS
    // --------
    this.sounds = {
        error:  this.game.add.audio('error', 0.2, false),
        rotate: this.game.add.audio('rotate', 0.1, false),
        shift:  this.game.add.audio('shift', 0.02, false),
        leftright:  this.game.add.audio('leftright', 0.15, false)
        //smilee: this.game.add.audio('snd_smilee', 1, false),
        //dud: this.game.add.audio('snd_dud', 1, false)
    }
        
        
    }

    update() {

        if (this._checkKeyStates()) {

            // console.log(gamestate.cursors);

            this._doKeyActions();

        }

        if (!this.isAnimating && this.keyQueue.length > 0) {
            this._act();
        }

        // console.log('===================================', this.keyQueue);

    }

    hazWinning() {
        // console.log("Winning condition: ", this.level.allConnected());

        if (this.level.allConnected()) {
            this.infobox = this.add.sprite(18,12,'background');

            var style_press = { font: "italic 23px Arial", fill: "#000000", align: "center" };

            var text = null;
            // console.log(typeof leveldata.level[this.level+1], this.level);
            // console.log(leveldata, leveldata[this.level+1], typeof leveldata[this.level+1]);
            // LAST LEVEL
            if (this.level == 11 ) {
                ga('send', 'event', 'LD#35', 'finished GAME', this.level);
                var text = this.add.text(200, 270,
                    'You just finished Level '+ gamestate.level +
                    '\rThats it for now, i hope you liked it!\r' +
                    '\rThanks for playing, come back soon :)', {fill: "#666666"});
                gamestate.status = 'done';
            } else {
                ga('send', 'event', 'LD#35', 'finished Level', this.level);
                var text = this.add.text(240, 240,
                    "You just finished Level "+ gamestate.level +
                    "\rNice one, but there is more.\r" +
                    "\rCheck out the next level!", {fill: "#666666"});

                this.text = this.add.text(250, 500, "Press any key or mouse button to go to next level", style_press);
                gamestate.status = 'winning';
            }
        }
    }

    onDown(event) {

        if (gamestate.status == 'winning') {
            gamestate.status = 'playing';
            ga('send', 'event', 'LD#35', 'starting level', this.level);
            this.nextLevel();
        }

        // process pausemenu input
        if( this.game.paused ) {

            var choice = this.pausemenu.getChoice(event);

            // console.log('pausemenu choice: ', choice);

        }

    }
    
    _act() {

        if (gamestate.status == 'winning') {
            gamestate.status = 'playing';
            this.nextLevel();
        }

        switch(this.keyQueue.shift()) {
        case 'r':
            this.isAnimating = true;
            // gamestate.selector.moveRight();
            this.level.shiftRight();
            break;
        case 'l':
            this.isAnimating = true;
            // gamestate.selector.moveLeft();
            this.level.shiftLeft();
            break;
        case 'u': 
            this.isAnimating = true;
            gamestate.selector.moveUp();
            // this.level.shiftUp();
            break;
        case 'd': 
            this.isAnimating = true;
            gamestate.selector.moveDown();
            // this.level.shiftDown();
            break;
        case 'a':
            this.isAnimating = true;
            this.level.rotate('-90');
            // this.nextLevel();
            break;
        case 's':
            this.isAnimating = true;
            this.level.rotate();
            // this.restartLevel();
            break;
        case 'reset':
            this.isAnimating = true;
            this.restartLevel();
            break;
        case 'space':
            this.isAnimating = true;
            this.level.rotate();
            // gamestate.selector.rotateCW();
            break;
        }
        
    }

    restartLevel() {
        this.game.state.start( this.game.state.current );
    }

    nextLevel() {
        gamestate.level++;
        this.game.state.start( this.game.state.current );
    }


    _doKeyActions() {
        
        var currkey = '';
        
        // LEFT
        if (gamestate.cursors.leftdown && !gamestate.cursors.leftacted) {
            currkey = 'l';
            gamestate.cursors.leftacted = true;
        }

        // RIGHT
        if (gamestate.cursors.rightdown && !gamestate.cursors.rightacted) {
            currkey = 'r';
            gamestate.cursors.rightacted = true;
        }

        // UP
        if (gamestate.cursors.updown && !gamestate.cursors.upacted) {
            currkey = 'u';
            gamestate.cursors.upacted = true;
        }

        // DOWN
        if (gamestate.cursors.downdown && !gamestate.cursors.downacted) {
            currkey = 'd';
            gamestate.cursors.downacted = true; 
        }

        // SPACE
        if (gamestate.keys.spacedown && !gamestate.keys.spaceacted) {
            currkey = 'space';
            gamestate.keys.spaceacted = true;
        }

        // A
        if (gamestate.keys.adown && !gamestate.keys.aacted) {
            currkey = 'a';
            gamestate.keys.aacted = true;
        }

        // S
        if (gamestate.keys.sdown && !gamestate.keys.sacted) {
            currkey = 's';
            gamestate.keys.sacted = true;
        }

        // r
        if (gamestate.keys.rdown && !gamestate.keys.racted) {
            currkey = 'reset';
            gamestate.keys.racted = true;
        }

        if (currkey !== '') {
            this.keyQueue.push(currkey);
            // console.log('===================================>', this.keyQueue);
        }

    }

    _checkKeyStates() {

        var statechange = false;

        // LEFT
        // =============
        if (this.cursors.left.isDown && !gamestate.cursors.leftdown) {
            gamestate.cursors.leftdown = true;
            gamestate.cursors.leftacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.cursors.left.isDown && gamestate.cursors.leftdown) {
            gamestate.cursors.leftdown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // UP
        // =============
        if (this.cursors.up.isDown && !gamestate.cursors.updown) {
            gamestate.cursors.updown = true;
            gamestate.cursors.upacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.cursors.up.isDown && gamestate.cursors.updown) {
            gamestate.cursors.updown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // RIGHT
        // =============
        if (this.cursors.right.isDown && !gamestate.cursors.rightdown) {
            gamestate.cursors.rightdown = true;
            gamestate.cursors.rightacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.cursors.right.isDown && gamestate.cursors.rightdown) {
            gamestate.cursors.rightdown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // DOWN
        // =============
        if (this.cursors.down.isDown && !gamestate.cursors.downdown) {
            gamestate.cursors.downdown = true;
            gamestate.cursors.downacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.cursors.down.isDown && gamestate.cursors.downdown) {
            gamestate.cursors.downdown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // SPACE
        // =============
        if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && !gamestate.keys.spacedown) {
            gamestate.keys.spacedown = true;
            gamestate.keys.spaceacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR) && gamestate.keys.spacedown) {
            gamestate.keys.spacedown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // A
        // =============
        if (this.game.input.keyboard.isDown(Phaser.Keyboard.A) && !gamestate.keys.adown) {
            gamestate.keys.adown = true;
            gamestate.keys.aacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.game.input.keyboard.isDown(Phaser.Keyboard.A) && gamestate.keys.adown) {
            gamestate.keys.adown = false;
            statechange = true;
            // LEFT UP
            // ...
        }

        // S
        // =============
        if (this.game.input.keyboard.isDown(Phaser.Keyboard.S) && !gamestate.keys.sdown) {
            gamestate.keys.sdown = true;
            gamestate.keys.sacted = false;
            statechange = true;
            // LEFT DOWN
            // ...

        } else if (!this.game.input.keyboard.isDown(Phaser.Keyboard.S) && gamestate.keys.sdown) {
            gamestate.keys.sdown = false;
            statechange = true;
        }

        // R
        // =============
        if (this.game.input.keyboard.isDown(Phaser.Keyboard.R) && !gamestate.keys.rdown) {
            gamestate.keys.rdown = true;
            gamestate.keys.racted = false;
            statechange = true;

        } else if (!this.game.input.keyboard.isDown(Phaser.Keyboard.R) && gamestate.keys.rdown) {
            gamestate.keys.rdown = false;
            statechange = true;
        }

        return statechange;
    }

}
