module FindTheWords {
    export class FindTheWords extends Base.BasicGroup {

        Elements: any;
        PREFIX: any;

        Words: any[];
        placedIndexes: number[];
        Size: number;
        Grid: any[];
        BoolGrid: any[];
        CharTable: any[];
        numberOfChecked: number;

        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();
            }

            if (this.json.isFirst == true) {
                EU.loadVocabulary(this);
            };
            EU.createStaticElements(this);
            EU.createSelectableElements(this);
            EU.createFillElements(this);
            this.numberOfChecked = 0;
            this.Size = 0;
            this.pickRandomWords();
            this.clearWhiteSpacesAndSort();
            this.initializeGrid();
            this.generateGrid();
            this.createGrid();
            this.createHelpWords();

        }

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

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

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

        private onInputDown(el: Phaser.Text, pointer) {

            if (this.CharTable[el.name].state == "unchecked") {
                if (this.Elements.MarkWrongAnswers && this.Elements.MarkWrongAnswers == true) {

                    if (this.CharTable[el.name].value == 1) {
                        this.CharTable[el.name].bg.tint = "0x99FF99";
                    }
                    else {
                        this.CharTable[el.name].bg.tint = "0xFF9999";
                    }
                }
                else {
                    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 pickRandomWords() {
            this.Words = [];
            for (var i = 0; i < this.Elements.NumberOfWords; i++) {
                var word;
                var answer;
                var flag = false;
                while (flag == false) {
                    flag = true;
                    var categoryIndex = Math.floor((Math.random() * EU.groups.length));
                    var wordIndex = Math.floor((Math.random() * EU.groups[categoryIndex].vocabulary.length));
                    EU.Log(categoryIndex + " " + wordIndex);
                    word = EU.groups[categoryIndex].vocabulary[wordIndex];
                    for (var i = 0; i < EU.usedWords.length; i++) {
                        if (EU.usedWords[i] == word.en) {
                            flag = false;
                            break;
                        }
                        flag = true;
                    }
                }
                this.Words.push(word);
                EU.usedWords.push(word.en);
                EU.Log(word.en);
            }
        }

        private clearWhiteSpacesAndSort() {
            for (var i = 0; i < this.Words.length; i++) {
                this.Words[i].en = this.Words[i].en.replace(/ |'|\.|,/g, '');
                this.Words[i].en = this.Words[i].en.toUpperCase();

            }
            this.Words = this.Words.sort(function (a, b) {
                return b.en.length - a.en.length; // ASC -> a - b; DESC -> b - a
            });
            this.Size = this.Words[0].en.length;
        }

        private initializeGrid() {
            this.Grid = [];
            this.BoolGrid = [];
            for (var i = 0; i < this.Size; i++) {
                var row = [];
                var val = [];
                for (var j = 0; j < this.Size; j++) {
                    row.push('0');
                    val.push(0);
                }
                this.Grid.push(row);
                this.BoolGrid.push(val);
            }
            EU.Log(this.Size);
            EU.Log(this.Grid.length / this.Size);
        }

        private addRowToGrid() {
            var row = [];
            var val = [];
            for (var j = 0; j < this.Size; j++) {
                row.push('0');
                val.push(0);
            }
            this.Grid.push(row);
            this.BoolGrid.push(val);
        }

        private fillGrid() {
            var chars = "QWERTYUIOPASDFGHJKLZXCVBNM";
            for (var j = 0; j < this.Grid.length; j++) {
                for (var k = 0; k < this.Grid[j].length; k++) {
                    if (this.Grid[j][k] == '0') {
                        var charIndex = Math.floor((Math.random() * chars.length));
                        this.Grid[j][k] = chars[charIndex];
                    }
                }
            }
        }

        private placeFirstWord() {
            var posIndex = Math.floor((Math.random() * this.Size));
            var dir = Math.floor((Math.random() * this.Elements.Directions));
            switch (dir) {
                case 0: // poziom
                    for (var i = 0; i < this.Size; i++) {
                        this.Grid[posIndex][i] = this.Words[0].en[i];
                        this.BoolGrid[posIndex][i] = 1;
                    }
                    break;
                case 1: // pion 
                    for (var i = 0; i < this.Size; i++) {
                        this.Grid[i][posIndex] = this.Words[0].en[i];
                        this.BoolGrid[i][posIndex] = 1;
                    }
                    break;
                case 2: //poziom rev
                    for (var i = 0; i < this.Size; i++) {
                        this.Grid[posIndex][i] = this.Words[0].en[this.Words[0].en.length - 1 - i];
                        this.BoolGrid[posIndex][i] = 1;
                    }
                    break;
                case 3: // pion rev
                    for (var i = 0; i < this.Size; i++) {
                        this.Grid[i][posIndex] = this.Words[0].en[this.Words[0].en.length - 1 - i];
                        this.BoolGrid[i][posIndex] = 1;
                    }
                    break;
            }
        }

        private placeWords() {
            this.placedIndexes = [];
            this.placedIndexes.push(0);
            var counter = 0;
            for (var i = 1; i < this.Words.length; i++) {
                var fits = false;
                for (var j = 0; j < this.Grid.length; j++) {
                    for (var k = 0; k < this.Grid[j].length; k++) {
                        if (this.Grid[j][k] != '0') {
                            for (var l = 0; l < this.Words[i].en.length; l++) {

                                if (this.Words[i].en[l] == this.Grid[j][k]) {
                                    for (var m = 0; m < this.Elements.Directions; m++) {
                                        if (this.checkIfFits(j, k, m, l, this.Words[i].en.length)) {
                                            if (this.checkWordCollision(j, k, m, l, this.Words[i].en)) {
                                                //EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " Fits! " + m);
                                                fits = true;
                                                counter++;
                                                this.placedIndexes.push(i);
                                                this.placeOneWord(j, k, m, l, this.Words[i].en);
                                                break;
                                            }
                                            else {
                                                // EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " NOFITWORD! " + m);
                                            }
                                        }
                                        else {
                                            // EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " NOFITSIZE! " + m);
                                        }
                                    }
                                    if (fits == true) break;
                                }
                            }
                        }
                        if (fits == true) break;
                    }
                    if (fits == true) break;
                }
            }
            EU.Log("Placed : " + (counter + 1));
        }

        private placeNotPlaced() {
            var counter = 0;
            for (var i = 1; i < this.Words.length; i++) {
                var isAlreadyPlaced = false;
                for (var z = 1; z < this.placedIndexes.length; z++) {
                    if (i == this.placedIndexes[z]) {
                        isAlreadyPlaced = true;
                        break;
                    }
                }
                if (isAlreadyPlaced == false) {
                    EU.Log(this.Words[i].en);
                    var fits = false;
                    var places = [];
                    for (var j = 0; j < this.Grid.length; j++) {
                        for (var k = 0; k < this.Grid[j].length; k++) {
                            for (var m = 0; m < this.Elements.Directions; m++) {
                                if (this.checkIfFits(j, k, m, 0, this.Words[i].en.length)) {
                                    if (this.checkWordCollision(j, k, m, 0, this.Words[i].en)) {
                                        //EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " Fits! " + m);
                                        fits = true;
                                        places.push({
                                            "j": j,
                                            "k": k,
                                            "m": m,
                                        });
                                    }
                                    else {
                                        //EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " NOFITWORD! " + m);
                                    }
                                }
                                else {
                                    //EU.Log(this.Words[i].en + " " + this.Words[i].en[l] + " NOFITSIZE! " + m);
                                }
                            }
                        }
                    }
                    if (fits == true) {
                        var rand = Math.floor((Math.random() * places.length));
                        this.placedIndexes.push(i);
                        this.placeOneWord(places[rand].j, places[rand].k, places[rand].m, 0, this.Words[i].en);
                        counter++;
                    }
                }
            }
            EU.Log("PlacedAfter : " + counter);
        }


        private checkIfFits(posX, posY, dir, at, length) {
            switch (dir) {
                case 0: // poziom
                    if (posX + length - at <= this.Size && posX - at >= 0) return true;
                    break;
                case 1: //pion
                    if (posY + length - at <= this.Size && posY - at >= 0) return true;
                    break;
                case 2:
                    EU.Log(posX + "+" + length + "-" + at + "+" + "-1  " + (posX + length - at - 1) + " " + length + " " + this.Size);
                    if (posX + (length - at + 1) <= this.Size && posX - (length - 1 - at) > 0) return true;
                    break;
                case 3:
                    if (posY + (length - at + 1) <= this.Size && posY - (length - 1 - at) > 0) return true;
                    break;
            }
            return false;
        }

        private checkWordCollision(posX, posY, dir, at, word) {
            switch (dir) {
                case 0: // poziom
                    for (var i = 0; i < word.length; i++) {
                        if (this.Grid[posX - at + i][posY] != '0')
                            if (this.Grid[posX - at + i][posY] != word[i]) return false;
                    };
                    break;
                case 1: //pion
                    for (var i = 0; i < word.length; i++) {
                        if (this.Grid[posX][posY - at + i] != '0')
                            if (this.Grid[posX][posY - at + i] != word[i]) return false;
                    };
                    break;
                case 2:
                    for (var i = 0; i < word.length; i++) {
                        EU.Log(posX + "+" + word.length + "-" + at + "+" + i + "-1  " + (posX + word.length - at - i - 1) + " " + word + " " + this.Size);
                        if (this.Grid[posX + word.length - at - i][posY] != '0')
                            if (this.Grid[posX + word.length - at - i][posY] != word[i]) return false;
                    };
                    break;
                case 3:
                    for (var i = 0; i < word.length; i++) {
                        if (this.Grid[posX][posY + word.length - at - i] != '0')
                            if (this.Grid[posX][posY + word.length - at - i] != word[i]) return false;
                    };

                    break;
            }
            return true;

        }

        private placeOneWord(posX, posY, dir, at, word) {
            switch (dir) {
                case 0: // poziom
                    for (var i = 0; i < word.length; i++) {
                        this.Grid[posX - at + i][posY] = word[i];
                        this.BoolGrid[posX - at + i][posY] = 1;
                    };
                    break;
                case 1: //pion
                    for (var i = 0; i < word.length; i++) {
                        this.Grid[posX][posY - at + i] = word[i];
                        this.BoolGrid[posX][posY - at + i] = 1;
                    };
                    break;
                case 2:
                    for (var i = 0; i < word.length; i++) {
                        this.Grid[posX + word.length - at - i][posY] = word[i];
                        this.BoolGrid[posX + word.length - at - i][posY] = 1;
                    };
                    break;
                case 3:
                    for (var i = 0; i < word.length; i++) {
                        this.Grid[posX][posY + word.length - at - i] = word[i];
                        this.BoolGrid[posX][posY + word.length - at - i] = 1;
                    };
                    break;
            }
        }

        private generateGrid() {
            this.placeFirstWord();
            this.placeWords();
            this.placeNotPlaced();
            EU.Log(this.placedIndexes.length);
            while (this.placedIndexes.length < 10) {
                this.addRowToGrid();
                this.placeNotPlaced();
            }
            this.fillGrid();
            EU.Log(this.placedIndexes.length);
        }

        createHelpWords() {
            var posX = this.Elements.HelpPosition.x;
            var posY = this.Elements.HelpPosition.y;
            if (this.Elements.Just) {
                switch (this.Elements.Just.x) {
                    case "center":
                        posX += (Global.Main.mainContainerDims.wd - 120) / 2;
                        break;
                    case "right":
                        posX += Global.Main.mainContainerDims.wd - 120;
                        break;
                }
                switch (this.Elements.Just.y) {
                    case "center":
                        posY += (Global.Main.mainContainerDims.hg - 65) / 2;
                        break;
                    case "bottom":
                        posY += Global.Main.mainContainerDims.hg - 65;
                        break;
                }
            }
            for (var i = 0; i < this.Words.length; i++) {
                var el = this.game.add.text(0, 0, this.Words[i].pl, this.Elements.Style);
                el.anchor.set(1, 0);
                el.position.set(posX, posY + i * el.height);
                this.addChild(el);
            }
        }

        createGrid() {
            this.CharTable = [];
            var posX = this.Elements.Position.x;
            var posY = this.Elements.Position.y;
            if (this.Elements.Just) {
                switch (this.Elements.Just.x) {
                    case "center":
                        posX += (Global.Main.mainContainerDims.wd - 120) / 2;
                        break;
                    case "right":
                        posX += Global.Main.mainContainerDims.wd - 120;
                        break;
                }
                switch (this.Elements.Just.y) {
                    case "center":
                        posY += (Global.Main.mainContainerDims.hg - 65) / 2;
                        break;
                    case "bottom":
                        posY += Global.Main.mainContainerDims.hg - 65;
                        break;
                }
            }
            for (var i = 0; i < this.Grid.length; i++) {
                for (var j = 0; j < this.Grid[i].length; j++) {
                    var el = this.game.add.text(0, 0, this.Grid[i][j], this.Elements.Style);
                    var bg = this.drawRect("lightblue", el.height, el.height);
                    var value = this.BoolGrid[i][j];
                    bg.name = (i * this.Size + j).toString();
                    el.anchor.set(0.5, 0);
                    el.position.set(posX + j * bg.width + bg.width / 2 - bg.height * this.Size / 2, posY + i * bg.height);
                    bg.inputEnabled = true;

                    bg.events.onInputOver.add(this.onInputOver, this);
                    bg.events.onInputOut.add(this.onInputOut, this);
                    bg.events.onInputDown.add(this.onInputDown, this);
                    bg.position.set(posX + j * bg.width - bg.height * this.Size / 2, posY + i * bg.height);
                    bg.addChild(el);
                    this.addChild(bg);
                    this.addChild(el);

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

        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);
        }

        checkIfWordsAreCorrect() {
            for (var i = 0; i < this.CharTable.length; i++) {

                if ((this.CharTable[i].value == 1 && this.CharTable[i].state == "unchecked") ||
                    (this.CharTable[i].value == 0 && this.CharTable[i].state == "checked")) {
                    return false;
                }
            }
            return true;
        }

        checkIfEverythingIsCorrect() {
            if (EU.checkIfFillsAreCorrect(this) && EU.checkIfSelectablesAreCorrect(this) &&
                this.checkIfWordsAreCorrect()) {
                EU.setGameCompletion(this.parent, 1);
                EU.Log("Correct!!!");
                return true;
            };
            EU.setGameCompletion(this.parent, 0);
            EU.Log("NotCorrect!!! :<");
            return false;
        }
    }
}   