module MainGame {
    export class Fill2 extends BasicModule.BasicState {
        connectElementCount: number;
        GameData: any;
        HorizontalPlacementArray: Array<number> = [];
        VerticalPlacementArray: Array<number> = [];
        tst2: any;
        text: Phaser.Text;
        item: any;
        box: any;
        public keyboard: any;
        isGrid: Boolean = false;
        StartingPosX: number = 0;
        StartingPosY: number = 0;
        Columns: number = 0;
        Rows: number = 0;
        Spacing: number = 0;
        initializationKeys: string = "";
        maxCharacters: number = 0;
        FillList: Array<any> = [];
        fontSize;
        helpBtn: any;
        cloud: Phaser.Image;
        cloudText: Phaser.Text;
        isHelpShown: boolean = false;
        guide: Phaser.Group;
        instruction: any;
        applause: any;
        firstRun: boolean = true;
        soundButton: any;
        soundBank: any;

        public inputBoxStyle = { font: "normal 80pt Arial", fill: "black" };

        constructor() {
            super();
        }

        preload() {
            console.log("preload");
            super.preload();
            // this.game.load.onLoadComplete.addOnce(this.create, this);
            this.loadGraphics();
            // this.loadSpritesheet();
            this.game.load.start();

            this.instruction = new Audio("./Sounds/ZIP_g_I_12_6.mp3");
            this.applause = new Audio("./Sounds/ZIP_g_I_12_11.mp3");
            this.game.load.image("cloud", "Graphics/gui/instr_bg.png");
            this.game.load.image("gameGuide", "Graphics/gui/guide.png");
            this.game.load.spritesheet("help", "Graphics/gui/help.png", 104, 108, 2, 0, 8);
            this.game.load.spritesheet("speaker", "Graphics/gui/ZIP_karta_pracy_button_glosnik.png", 136 / 2, 56, 2);
        }
        public killKeyborad() {
            if (this.keyboard != undefined) {

                this.keyboard.destroy(false, false);
                this.keyboard = undefined;
            }
        }
        create() {
            super.create();
            //}
            console.log("create");

            this.loadInit();
            // this.keyboardInit();
            this.createAdditionalElements();
            this.createStaticElements();
            this.createActiveElments();
            this.createControllElement();
            this.guide = this.game.add.group();
            var gd = this.game.add.image(this.game.width * 0.7, 0, "gameGuide");
            this.cloud = this.game.add.image(this.game.width * 0.5, 0, "cloud");
            gd.y = this.cloud.height * 0.8;
            this.cloudText = this.game.add.text(0, 0, "Przed Tobą ostatnie zadanie.", { wordWrap: true, wordWrapWidth: this.cloud.width * 0.75 });
            this.cloudText.anchor.set(0.5, 0.5);
            this.cloudText.position.setTo(this.cloud.width * 0.5, this.cloud.height * 0.47);
            this.cloud.addChild(this.cloudText);
            this.guide.addChild(this.cloud);
            this.guide.addChild(gd);
            this.guide.y = this.game.world.height;
            this.helpBtn = this.game.add.button(1778, 22, "help", this.showHelp, this, 0, 0, 1, 0);
            this.showHelp()



        } addSoundButton(obj: any, sound: any) {
            console.log(obj);
            this.soundButton = this.game.add.sprite(250, obj.y - obj.height / 2, "speaker");
            // this.soundButton.soundBankName = obj.Sound;
            this.soundButton.soundBankName = sound;
            // this.addChild(this.soundButton);
            this.soundButton.inputEnabled = true;
            this.soundButton.events.onInputUp.add(this.soundButtonDown, this);

        }
        soundButtonDown(button) {
            if (this.soundBank !== undefined)
                this.soundBank.pause();
            this.soundBank = new Audio(button.soundBankName);
            //this.soundBank.currentTime = 0;
            this.soundBank.play();
            // Global.Main.PlayMusic(this.soundBank);
           
            // this.soundBank = new Audio(button.soundBankName);
           
        }
        changeHelp() {
            this.showHelp();
            //this.helpBtn.inputEnabled = true;
            this.cloudText.y = this.cloud.height * 0.4;
            // //this.tipsBtn = this.game.add.button(this.cloud.width / 2, this.cloud.height * 0.7, "tips", this.showOutfits, this, 0, 0, 1, 0);
            // //this.tipsBtn.anchor.setTo(0.5, 0.5);
            // this.cloud.addChild(//this.tipsBtn);
            // this.button_play = this.game.add.button(818, 811, "_button", this.buttonPressed, this, 1, 0, 1, 0);
        }
        showWin() {
            
            //if (this.tableOutfits.length == 0) this.tableOutfits = [1, 2];
            //if (this.tipsBtn != undefined)
            //this.tipsBtn.visible = false;
            //this.ggCount++;
            var tw = this.game.add.tween(this.guide);
            this.cloudText.setText("Doskonale! Dotarłeś do szkoły. Gratulacje!");
            //if (this.halp != undefined)
            //    this.halp.visible = false;
            tw.to({ y: this.game.world.height - this.guide.height }, 800, Phaser.Easing.Cubic.Out);
            tw.onComplete.add(function () {
                this.game.time.events.add(Phaser.Timer.SECOND * 4, function () {
                    try {
                        this.applause.pause();
                        // this.applause.currentTime = 0;
                        //console.log("ZMAINA LEVELU");
                        //ZMIANA PLANSZY
                        // this.game.state.start("Fill");
                        this.game.state.start("TitleScreenState");
                        // this.reload(); 
                        //this.replay();
                    } catch (e) { }
                }, this);
            }, this);
            tw.start();


            try {
                // this.applause.currentTime = 0;
                this.applause.play();
            } catch (e) { }
        }
        showHelp() {

            var tw = null;
            this.cloudText.setText("Przeczytaj zdanie i policz:");
            var point = this.game.world.height;
            this.isHelpShown = !this.isHelpShown;

            if (this.isHelpShown) {
                point -= this.guide.height;
                try {
                    // this.instruction.currentTime = 0;
                    this.instruction.play();
                    if (this.firstRun) {
                        //this.helpBtn.inputEnabled = false;
                        var tmr = this.game.time.events.add(Phaser.Timer.SECOND * 4, this.changeHelp, this);
                    }
                } catch (e) { }
            } else {
                try {
                    this.instruction.pause();
                    // this.instruction.currentTime = 0;
                } catch (e) { }
            }

            tw = this.game.add.tween(this.guide);
            tw.to({ y: point }, 800, Phaser.Easing.Cubic.Out);
            tw.start();
            //this.button_play = this.game.add.button(818, 811, "_button", this.buttonPressed, this, 1, 0, 1, 0);
        }
        loadInit() {
            this.initializationKeys = this.GameData.AcceptedCharacters;
            this.maxCharacters = this.GameData.MaxCharacters;
            if (this.GameData.isGrid == true) {
                this.isGrid = this.GameData.isGrid;
                this.StartingPosX = this.GameData.StartingPos.x;
                this.StartingPosY = this.GameData.StartingPos.y;
                this.Columns = this.GameData.Columns;
                this.Rows = this.GameData.Rows;
                this.Spacing = this.GameData.Spacing;
            }
            // //EU.Log("isGrid?" + this.isGrid);
        }
        loadGraphics() {

            for (var i = 0; i < this.GameData.Graphics.length; i++)
                this.game.load.image(this.GameData.Graphics[i].key, this.GameData.Graphics[i].src);
        }
        loadSpritesheet() {
            for (var i = 0; i < this.GameData.Spritesheet.length; i++)
                this.game.load.spritesheet(this.GameData.Spritesheet[i].key, this.GameData.Spritesheet[i].src, this.GameData.Spritesheet[i].size.x, this.GameData.Spritesheet[i].size.y, this.GameData.Spritesheet[i].size.no);
        }
        createControllElement() {
            for (var i = 0; i < this.GameData.Controlls.length; i++) {
                var el = this.game.add.image(this.GameData.Controlls[i].pos.x, this.GameData.Controlls[i].pos.y, this.GameData.Controlls[i].key);
                // el.anchor.set(0.5);
                //this.addChild(el);
            }
        }
        createAdditionalElements() {
            for (var i = 0; i < this.GameData.AditionalElements.length; i++) {
                var el = this.game.add.image(this.GameData.AditionalElements[i].pos.x, this.GameData.AditionalElements[i].pos.y, this.GameData.AditionalElements[i].key);
                // el.anchor.set(0.5);
                //this.addChild(el);
            }
        }

        createStaticElements() {
            if (this.GameData.CustomFontSize != -1) {
                this.fontSize = this.GameData.CustomFontSize;
                var LetterAmountmultipler = 70 * (this.maxCharacters / 3);
            }
            else {
                this.fontSize = 50 - (this.maxCharacters);
                var LetterAmountmultipler = 70 * (this.maxCharacters / 3);
            }
            this.inputBoxStyle.font = "normal " + this.fontSize + "pt Arial";
            if (this.isGrid) {
                var currHeight = this.StartingPosY;

                for (var i = 0; i < this.GameData.StaticElements.length; i++) {

                    var currWidth = this.StartingPosX;
                    if (this.GameData.StaticElements[i].HasImage) {
                        var el = this.game.add.image(currWidth, currHeight + (100 * i), this.GameData.StaticElements[i].key);
                        //el.anchor.set(0.5, 0.5);
                        el.scale.setTo(0.5, 0.5);
                        currWidth += el.width;
                        currHeight += el.height;
                        this.HorizontalPlacementArray.push(currWidth + this.Spacing);
                        this.VerticalPlacementArray.push(el.height / 2 + this.Spacing);
                        //this.addChild(el);
                    }
                    if (this.GameData.StaticElements[i].HasText) {

                        var el_text = this.game.add.text(this.GameData.StaticElements[i].pos.x, this.GameData.StaticElements[i].pos.y, this.GameData.StaticElements[i].prefix, this.inputBoxStyle);
                        el_text.anchor.set(0, 0.5);
                        //this.HorizontalPlacementArray.push(el_text.width + (LetterAmountmultipler / 2) + currWidth);
                        //this.addChild(el_text);
                    
                        // this.createActiveTextElment(currWidth, currHeight + (100 * i), this.GameData.StaticElements[i].id);
                       
                        el_text = this.game.add.text(this.HorizontalPlacementArray[i] + LetterAmountmultipler / 2, currHeight + (100 * i), this.GameData.StaticElements[i].sufix, this.inputBoxStyle);
                        el_text.anchor.set(0, 0.5);
                        currWidth += el_text.width;
                        this.VerticalPlacementArray.push(currHeight + (100 * i));
                        //this.addChild(el_text);
                    }
                }
            } else {
                for (var i = 0; i < this.GameData.StaticElements.length; i++) {
                    var el = this.game.add.image(this.GameData.StaticElements[i].pos.x, this.GameData.StaticElements[i].pos.y, this.GameData.StaticElements[i].key);
                    // el.anchor.set(0.5);
                    //this.addChild(el);
                }
            }
        }

        createActiveElments() {

            if (this.GameData.CustomFontSize != -1) {
                this.fontSize = this.GameData.CustomFontSize;
            }
            else {
                this.fontSize = 50 - (this.maxCharacters);
            }
            var BoxSize = 8 / 5 * this.fontSize;
            var LetterAmountmultipler = 70 * (this.maxCharacters / 3);

            this.inputBoxStyle.font = "normal " + this.fontSize + "pt Arial";
            var bmd = this.game.add.bitmapData(LetterAmountmultipler, BoxSize);
            bmd.ctx.rect(0, 0, LetterAmountmultipler, BoxSize);
            bmd.ctx.fillStyle = '#cdcdcd';
            bmd.ctx.fill();

            var currHeight = this.StartingPosY;
            for (var i = 0; i < this.GameData.TaskList.length; i++) {

                //this.box = this.game.add.sprite(this.HorizontalPlacementArray[i], this.VerticalPlacementArray[i], bmd);
                //else
                this.box = this.game.add.sprite(this.GameData.TaskList[i].pos.x, this.GameData.TaskList[i].pos.y, bmd);

                this.box.anchor.set(0.5, 0.5);
                this.box.alpha = 0.5;
                //this.box.height = 100;
                this.box.width = LetterAmountmultipler;
                this.item = this.game.add.text(0, 0, "", this.inputBoxStyle);
                // this.box.width = this.item.width + 50;
                this.item.anchor.set(0.5, 0.5);
                this.item.father = this.box;
                this.item.x = this.box.x;
                this.item.y = this.box.y;
                //this.addChild(this.item);
                this.box.text = this.item;
                this.item.answer = this.GameData.TaskList[i].Answer;
                this.box.inputEnabled = true;
                this.box.events.onInputUp.add(this.showKeyboard, this);
                //this.addChild(this.box);
                this.FillList.push(this.item);
                this.addSoundButton(this.box, this.GameData.TaskList[i].Sound);
            }


        }

        keyboardInit() {
            // super.nextTask();
            this.keyboard = new KB.Keyboard(this.game, this.initializationKeys, 500, 0, true);
            if (this.initializationKeys.length >= 2) {
                //EU.Log(this.keyboard);
                this.keyboard.initialize(this.initializationKeys, "key", "key");
            }
            else {
                this.keyboard.initialize("qwertyuiop" + this.keyboard.arrSeparator + "asdfghjkl" + this.keyboard.arrSeparator + "zxcvbnm^&", "key", "key");
            }
            //}
                
            this.keyboard.scale.setTo(0.5, 0.5);
            this.keyboard.alive = false;
            this.keyboard.fixedToCamera = true;
            this.keyboard.maxLetters = this.maxCharacters;
            this.game.add.existing(this.keyboard);
            ////this.addChild(this.keyboard);          
            // lis.add(this.checkComplition);
        }
        showKeyboard(button) {
            if (this.keyboard == undefined)
                this.keyboardInit();
            ////EU.Log(button.width);
            // this.keyboardInit();
            this.keyboard.controller = button.text;
            this.keyboard.RootController = this;
            this.keyboard.navClick(this.keyboard);
            // //EU.Log(this.keyboard.input.text);
            // //EU.Log("test");
            //  console.log;
            // this.ShowKeyboard = true;
        }
        public checkComplition() {


            var TotalAnswers = this.GameData.TaskList.length;
            var GoodAnswers = 0;
            var BadAnswers = 0;
            for (var i = 0; i < this.GameData.TaskList.length; i++) {
                //console.log(this.FillList[i].text + " == " + this.GameData.TaskList[i].Answer.toUpperCase());
                if (this.FillList[i].text.toUpperCase() == this.GameData.TaskList[i].Answer.toUpperCase()) {
                    // TotalAnswers++;
                    GoodAnswers++;
                }
                else {
                    if (this.FillList[i].text.toUpperCase() != "?")
                        //TotalAnswers++;
                        BadAnswers++;
                }

            }
            if (TotalAnswers == GoodAnswers) {
                this.showWin();
                //console.log("All Good!");
                //EU.setGameCompletion(this.parent, 1);
            }
            else {
                var complition = GoodAnswers / TotalAnswers;
                var tmpCheck = BadAnswers / TotalAnswers;
                //EU.Log(complition + " + " + tmpCheck + " = " + (tmpCheck + complition));
                if (tmpCheck + complition != 1) {
                    //EU.Log("zaznacz wszystkie ocje");
                }
                else {
                    //EU.setGameCompletion(this.parent, 0);
                }

            }
            this.killKeyborad()
        }
        update() {
            
            //   this.tst2.text.slice(-1);
        }
        init(json) {
            //super.init(json);
            //ladowanie danych wejsciowych
            // //EU.Log(json);
            this.GameData = {
                "Title": "",
                "Sound": "ZIP_spr_I_8_7.mp3",
                "MaxCharacters": 10,
                "AcceptedCharacters": "0123456789",
                "isGrid": false,
                "StartingPos": { "x": 100, "y": 700 },
                "Columns": 4,
                "Rows": 2,
                "Spacing": 20,
                "CustomFontSize": 50,

                "Graphics":
                [
                    { "src": "Graphics/game/ZIP_g_I_12_zdanie.png", "key": "ZIP_g_I_11_zad1_image3" },
                    { "src": "Graphics/game/ZIP_g_I_12_zdanie2.png", "key": "ZIP_g_I_12_zdanie2" },
                    { "src": "Graphics/game/ZIP_g_I_12_zdanie3.png", "key": "ZIP_g_I_12_zdanie3" },
                    { "src": "Graphics/game/ZIP_g_I_12_zdanie4.png", "key": "ZIP_g_I_12_zdanie4" },
                    { "src": "Graphics/game/ZIP_g_I_12_zdanie5.png", "key": "ZIP_g_I_12_zdanie5" },

                ],
                "Spritesheet":
                [
                    // { "src": "Graphics/game/ZIP_g_I_6_next.png", "key": "ZIP_g_I_6_next", "size": { "x": 120, "y": 120, "no": 2 } },
                ],
                "Controlls":
                [
                    { "key": "ZIP_g_I_11_zad1_image3", "pos": { "x": 300, "y": 200 }, },
                    { "key": "ZIP_g_I_12_zdanie2", "pos": { "x": 650, "y": 400 }, },
                    { "key": "ZIP_g_I_12_zdanie3", "pos": { "x": 650, "y": 500 }, },
                    { "key": "ZIP_g_I_12_zdanie4", "pos": { "x": 650, "y": 600 }, },
                    { "key": "ZIP_g_I_12_zdanie5", "pos": { "x": 650, "y": 700 }, },
                    //{ "key": "ZIP_g_I_12_zdanie2", "pos": { "x": 1200, "y": 200 }, },
                    //{ "key": "ZIP_g_I_11_zad1_image3", "pos": { "x": 400, "y": 600 }, },
                    //{ "key": "ZIP_g_I_11_zad1_image4", "pos": { "x": 1000, "y": 600 }, },
                ],
                "AditionalElements":
                [

                    // { "key": "ZIP_g_I_10_zegar", "pos": { "x": 150, "y": 65 } },
                    // { "key": "ZIP_g_I_7_image", "pos": { "x": 200, "y": 120 } },
                ],
                "StaticElements":
                [
                    // { "HasText": true, "HasImage": false, "prefix": "Zegar wskazuje godzinę:", "sufix": "", "id": 1, "key": "", "pos": { "x": 100, "y": 800 } },
                    // { "HasText": true, "HasImage": false, "prefix": "", "sufix": "", "id": 2, "key": "", "pos": { "x": 270, "y": 265 } },
                    // { "HasText": true, "HasImage": false, "prefix": "", "sufix": "", "id": 3, "key": "", "pos": { "x": 270, "y": 465 } },
                    // { "HasText": true, "HasImage": false, "prefix": "", "sufix": "", "id": 4, "key": "", "pos": { "x": 900, "y": 65 } },
                ],
                "TaskList":
                [
                    { "Sound": "./Sounds/ZIP_g_I_12_7.mp3", "pos": { "x": 500, "y": 400 }, "Answer": "11", "id": 1 },
                    { "Sound": "./Sounds/ZIP_g_I_12_8.mp3", "pos": { "x": 500, "y": 500 }, "Answer": "2", "id": 1 },
                    { "Sound": "./Sounds/ZIP_g_I_12_9.mp3", "pos": { "x": 500, "y": 600 }, "Answer": "29", "id": 1 },
                    { "Sound": "./Sounds/ZIP_g_I_12_10.mp3", "pos": { "x": 500, "y": 700 }, "Answer": "10", "id": 1 },
                   // { "pos": { "x": 550, "y": 800 }, "Answer": "Kałuża", "id": 2 },
                    // { "pos": { "x": 860, "y": 545 }, "Answer": "1", "id": 3 },
                    //  { "pos": { "x": 860, "y": 670 }, "Answer": "1", "id": 4 },
                ]
            };
            
            //this.elementArr.push({ "Title": "1. Wpisz odpowiednia literkę 'w' lub 'f' w wyrazach.", "Sound": "MW_kp_I_1_0.mp3","maxcharacters": "1", });
            //  this.connectElementCount = 8;
            
            //1. Wpisz odpowiednia literkę 'w' lub 'f' w wyrazach.
            //dzwięk: MW_kp_I_1_0.mp3

            //foka f
            //flaga f
            //waga w
            //futro f
            //kowal w
            //kawa w
            //worek w
            //kilof f
        }

    }

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////            FORMAT JSONA           ////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//    JSON = {
//              completeText: "caly tekst do wyswietlenia",
//              searched: [["znak lub wyraz", (true/false || true szuka znaku lub wyrazu oddzielonego spacjami, kropka, myslnikiem lub cudzyslowiem; false szuka podciągu)], [], []]    
//           }
 