module WordSearch {
    export class WordSearch extends Base.BasicGroup {

        Elements: any;
        PREFIX: any;
        numberOfChecked: number;
        CharTable: any[];
 
        constructor(game, name, x, y, json) {
            super(game, name, x, y, json);
        }

        preload() {
            super.preload();
            this.game.load.onLoadComplete.addOnce(this.create, this);
            this.PREFIX = this.Elements.TaskPrefix;
            this.loadGraphics();
            this.game.load.start();
        }
        loadGraphics() {

            for (var i = 0; i < this.Elements.Graphics.length; i++)
                this.game.load.image(this.PREFIX + this.Elements.Graphics[i].key, this.Elements.Graphics[i].src);
        }

        create() {
            if (this.json.isStandalone) {
                super.create();
            }
            this.numberOfChecked = 0;
            this.createStaticElements();
            this.createCharTable();
        }

        init(json) {
            super.init(json);
            this.Elements = json.GameData;
        }

        createStaticElements() {
            if (this.Elements.StaticElements)
                for (var i = 0; i < this.Elements.StaticElements.el.length; i++) {
                    var el;
                    switch (this.Elements.StaticElements.el[i].type) {
                        case "image":
                            el = this.game.add.image(0, 0, this.PREFIX + this.Elements.StaticElements.el[i].key);
                            break;
                        case "text":
                            el = this.game.add.text(0, 0, this.Elements.StaticElements.el[i].text, this.Elements.StaticElements.Options.Style);
                            break;
                        case "sound":
                            el = this.game.add.sprite(0, 0, "speaker");
                            el.inputEnabled = true;
                            el.name = this.Elements.StaticElements.el[i].sound;
                            el.events.onInputUp.add(this.soundButtonDown, this);
                            break;
                    }
                    var posX = this.Elements.StaticElements.el[i].pos.x;
                    var posY = this.Elements.StaticElements.el[i].pos.y;
                    if (this.Elements.StaticElements.Options.Just) {
                        switch (this.Elements.StaticElements.Options.Just.x) {
                            case "center":
                                posX += (Global.Main.mainContainerDims.wd - 120) / 2;
                                el.anchor.x = 0.5;
                                break;
                            case "right":
                                posX += Global.Main.mainContainerDims.wd - 120;
                                el.anchor.x = 1;
                                break;
                        }
                        switch (this.Elements.StaticElements.Options.Just.y) {
                            case "center":
                                posY += (Global.Main.mainContainerDims.hg - 65) / 2;
                                el.anchor.y = 0.5;
                                break;
                            case "bottom":
                                posY += Global.Main.mainContainerDims.hg - 65;
                                el.anchor.y = 1;
                                break;
                        }
                    }
                    el.position.set(posX, posY);
                    this.addChild(el);
                }
        }


        createCharTable() {
            this.CharTable = [];

            for (var i = 0; i < this.Elements.TableSize.Rows; i++) {
                for (var j = 0; j < this.Elements.TableSize.Columns; j++) {
                    var el = this.game.add.text(0, 0, this.Elements.CharTable[i * this.Elements.TableSize.Columns + j], this.Elements.Style);
                    var bg = this.drawRect("lightyellow", el.height, el.height);
                    var value = this.Elements.BoolTable[i * this.Elements.TableSize.Columns + j];
                    el.name = (i * this.Elements.TableSize.Columns + j).toString();
                    
                    el.anchor.set(0.5,0);
                    el.position.set(this.Elements.Position.x + j * bg.width + bg.width / 2, this.Elements.Position.y + i * bg.height);
                    el.inputEnabled = true;
                    el.events.onInputOver.add(this.onInputOver, this);
                    el.events.onInputOut.add(this.onInputOut, this);
                    el.events.onInputDown.add(this.onInputDown, this);
                    bg.position.set(this.Elements.Position.x + j * bg.width, this.Elements.Position.y + i * bg.height);
                    this.addChild(bg);
                    this.addChild(el);

                    this.CharTable.push({
                        "text": el,
                        "bg": bg,
                        "value": value,
                        "state": "unchecked"
                    });

                }
            }
        }



        soundButtonDown(button) {
            Global.Main.PlayMusic(new Audio(button.name));
        }

        drawRect(color, width, height) {
            var drawnObject;
            //var width = 100; // example;
            //var height = 40; // example;
            var bmd = this.game.add.bitmapData(width, height);
            bmd.ctx.beginPath();
            bmd.ctx.rect(0, 0,width, height);
            bmd.ctx.stroke();
            bmd.ctx.fillStyle = color;
            bmd.ctx.fill();
            bmd.ctx.stroke();
            return this.game.add.sprite(0, 0, bmd);
        }

        //input

        private onInputOver(el: Phaser.Text, pointer) {
            el.alpha = 0.5;
        }

        private onInputOut(el: Phaser.Text, pointer) {
            el.alpha = 1.0;
        }

        private onInputDown(el: Phaser.Text, pointer) {
            if (this.CharTable[el.name].state == "unchecked") {
                this.CharTable[el.name].bg.tint = "0x99FF99";
                this.CharTable[el.name].state = "checked";
                this.numberOfChecked++;
            }
            else {
                this.CharTable[el.name].bg.tint = "0xFFFFFF";
                this.CharTable[el.name].state = "unchecked";
                this.numberOfChecked--;
            }
            this.checkIfEverythingIsCorrect();
        }

        private checkIfEverythingIsCorrect() {

            var srt = "Points: " + this.calculatePlayerPoints()
                + "/" + this.calculateMaxPoints();
            EU.Log(srt);
            EU.Log("Checked: " + this.numberOfChecked);

            if (this.calculatePlayerPoints() == this.calculateMaxPoints()
                && this.numberOfChecked == this.calculateMaxPoints()) {
                EU.setGameCompletion(this.parent, 1);
                EU.Log("Correct!!!");
                return true;
            }
            EU.setGameCompletion(this.parent, 0);
            return false;
            
        }

        private calculateMaxPoints() {
            return (this.Elements.BoolTable.split("1").length - 1);  
        }

        private calculatePlayerPoints() {
            var points = 0;
            for (var i = 0; i < this.CharTable.length; i++) {
                if (this.CharTable[i].value == "1" && this.CharTable[i].state == "checked") {
                    points++;
                }
            }
            return points;
           
        }


    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////            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)], [], []]    
//           }
/*

 {
           "attrs": ["TestGroupName", {
               "GameType": GameTypes.WordSearch,
               "description": "3. Znajdź 8 nazw ptaków. Możesz je zaznaczać poziomo, pionowo, ukośnie i wspak.",
               "Lector": "MW_kp_I_3_3.mp3",
               "MaxPoints": 1, "isStandalone": false, "isFirst": false, "GameData": {
                   "TaskPrefix": "Zad3",
                   "Graphics":
                       [

                       ],
                   "StaticElements":
                      {
                          "el": [],
                          "Options": {},
                      },

                   "TableSize": { "Columns": 8, "Rows": 8,},
                   "Style": { font: "60px Arial", fill: 'black' },
                   "Position": { "x": 550, "y": 100 },
                   
                   "CharTable":
                       
                           "krxsybap"+
                           "dudekvkb"+
                           "nlroayło"+
                           "hiskzjóc"+
                           "ugocwxki"+
                           "wróbelsa"+
                           "sawemwan"+
                           "kkapzsjn"
                       ,

                   "BoolTable":

                           "10000010"+
                           "11111011"+
                           "01100011"+
                           "01010011"+
                           "01000011"+
                           "11111111"+
                           "01111011"+
                           "01111110"
                       ,

               }
           }]
       },



*/