var canvas;
/** @type {CanvasRenderingContext2D} */
var ctx;
/** @type {Array} */
var game = [];
/** @type {Array} */
var players = [];
var fieldCount = 0;
var playerCount = 0;
var currentPlayer = 0;
var doubleBuff = false;
var igniteBuff = false;
var frostBuff = false;
var nextplayer = true;
var inAnimation = false;

class Field {
    constructor(id, x, y) {
        this.id = id;
        this.x = x;
        this.y = y;
        this.color = "yellow";
        this.extrafield = 0;
        this.ignited = false;
        this.igniteID = -1;
    }
    draw() {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, 20, 0, 2 * Math.PI);
        ctx.fill();
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.font = "20px Arial"
        ctx.fillStyle = "black";
        ctx.fillText(this.id, this.x, this.y, 32);
    }
}

class Player {
    constructor(color) {
        this.color = color;
        this.image = new Image();
        this.image.src = "img/" + color + ".png";
        this.position = 0;
        this.setField(game[0]);
        this.spells = [true, true, true];
        this.spellsTemporary = [false, false, false];
        this.skipTurn = false;
    }
    setField(field) {
        this.position = field.id;
        this.x = field.x - 10;
        this.y = field.y - 20;
    }
    draw() {
        ctx.drawImage(this.image, this.x, this.y, 20, 40);
    }
    spell(x) {
        if (!inAnimation) {
            if (this.spells[x - 1]) {
                switch (x) {
                    case 1:
                        this.spellsTemporary[x - 1] = !this.spellsTemporary[x - 1];
                        if (!igniteBuff) {
                            igniteBuff = true;
                            document.getElementById("ability" + x).style.backgroundColor = "blue";
                        } else {
                            igniteBuff = false;
                            document.getElementById("ability" + x).style.backgroundColor = "green";
                        }
                        break;
                    case 2:
                        this.spellsTemporary[x - 1] = !this.spellsTemporary[x - 1];
                        if (!doubleBuff) {
                            doubleBuff = true;
                            document.getElementById("ability" + x).style.backgroundColor = "blue";
                        } else {
                            doubleBuff = false;
                            document.getElementById("ability" + x).style.backgroundColor = "green";
                        };
                        break;
                    case 3:
                        this.spellsTemporary[x - 1] = !this.spellsTemporary[x - 1];
                        if (!frostBuff) {
                            frostBuff = true;
                            document.getElementById("ability" + x).style.backgroundColor = "blue";
                        } else {
                            frostBuff = false;
                            document.getElementById("ability" + x).style.backgroundColor = "green";
                        };
                        break;
                }
            }

        }
    }
}

function init(x) {
    playerCount = x;
    document.getElementById("gamemode").style.display = "none";
    document.getElementById("game").style.display = "block";
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    generateFields();
    addPlayers();
    redraw();
}

function generateFields() {
    for (let i = 1; i <= 9; i++) {
        game.push(new Field(fieldCount++, i * 60, 60));
    }

    game.push(new Field(fieldCount++, 540, 120));
    game.push(new Field(fieldCount++, 540, 180));
    game.push(new Field(fieldCount++, 540, 240));

    for (let i = 9; i >= 1; i--) {
        game.push(new Field(fieldCount++, i * 60, 300));
    }

    game.push(new Field(fieldCount++, 60, 360));
    game.push(new Field(fieldCount++, 60, 420));
    game.push(new Field(fieldCount++, 60, 480));

    for (let i = 1; i <= 9; i++) {
        game.push(new Field(fieldCount++, i * 60, 540));
    }

    // Start mező
    game[0].color = "lime";
    // Cél
    game[32].color = "lime";

    // Kimarad egy körből
    for (const index of [6, 15, 22, 30]) {
        game[index].extraField = 1;
        game[index].color = "aqua";
    }

    // Mégegyszer jön
    for (const index of [9, 16, 25]) {
        game[index].extraField = 2;
        game[index].color = "magenta";
    }

    // Visszatölti a képességeket
    for (const index of [1, 11, 21]) {
        game[index].extraField = 3;
        game[index].color = "darkblue";
    }
}

function addPlayers() {
    players.push(new Player("blue"));
    players.push(new Player("green"));
    if (playerCount > 2) {
        players.push(new Player("red"));
        if (playerCount == 4) {
            players.push(new Player("yellow"));
        }
    }
    players[currentPlayer].image.onload = function () {
        players[currentPlayer].draw();
    }
}

function redraw() {
    ctx.clearRect(0, 0, 600, 600);
    for (let i = 0; i < fieldCount; i++) {
        game[i].draw();
    }
    for (let i = 0; i < playerCount; i++) {
        players[i].draw();
    }
}

function nextStep(amount) {
    nextplayer = false;
    document.getElementById("roll").disabled = true;
    // Ha a játékos másik játékosra lépne
    if (amount != 0) {
        while (isThereAPlayer(players[currentPlayer].position + amount)) {
            amount++;
        }
    }
    // Ha túl sokat lépne a játékos vagy túl keveset
    if (amount > 32 - players[currentPlayer].position) {
        amount = 32 - players[currentPlayer].position;
    }
    if (amount < -players[currentPlayer].position) {
        amount = -players[currentPlayer].position;
    }
    animateToNextField(amount);
}

function isThereAPlayer(pos) {
    for (let i = 0; i < playerCount; i++) {
        if (players[i].position == pos) {
            return true;
        }
    }
}

function endStep() {
    if (players[currentPlayer].position == 32) {
        winner(players[currentPlayer].color);
        return;
    }
    if (game[players[currentPlayer].position].ignited) {
        animateToNextField(-1);
    } else {
        // Extra mező
        switch (game[players[currentPlayer].position].extraField) {
            case 1:
                // Kimarad egy körből
                players[currentPlayer].skipTurn = true;
                break;
                // Mégegyszer jön nem itt van kezelve (2)
            case 3:
                // Újratölti a képességeit
                players[currentPlayer].spells = [true, true, true];
                players[currentPlayer].spellsTemporary = [false, false, false];
                break;
            default:
                break;
        }
        // Teszteli, ha a következő játékos kimaradna
        while (players[(currentPlayer + 1) % playerCount].skipTurn) {
            currentPlayer = (currentPlayer + 1) % playerCount;
            players[currentPlayer].skipTurn = false;
        }
        // Következő játékos, ha nem mégegyszer jön
        if (game[players[currentPlayer].position].extraField != 2) {
            currentPlayer = (currentPlayer + 1) % playerCount;
        }
        nextplayer = true;
        document.getElementById("roll").disabled = false;
        switch (currentPlayer) {
            case 0:
                document.getElementById("nextPlayer").src = "img/blue.png";
                document.getElementById("nextPlayer").title = "Kék játékos";
                document.getElementById("nextPlayerColor").innerHTML = "Kék";
                break;
            case 1:
                document.getElementById("nextPlayer").src = "img/green.png";
                document.getElementById("nextPlayer").title = "Zöld játékos";
                document.getElementById("nextPlayerColor").innerHTML = "Zöld";
                break;
            case 2:
                document.getElementById("nextPlayer").src = "img/red.png";
                document.getElementById("nextPlayer").title = "Piros játékos";
                document.getElementById("nextPlayerColor").innerHTML = "Piros";
                break;
            case 3:
                document.getElementById("nextPlayer").src = "img/yellow.png";
                document.getElementById("nextPlayer").title = "Sárga játékos";
                document.getElementById("nextPlayerColor").innerHTML = "Sárga";
                break;
            default:
                document.getElementById("nextPlayer").src = "img/blue.png";
                document.getElementById("nextPlayer").title = "Kék játékos";
                document.getElementById("nextPlayerColor").innerHTML = "Kék";
        }
        game.forEach((element, index, array) => {
            if (element.igniteID == currentPlayer) {
                var array1 = [6, 15, 22, 30];
                var array2 = [9, 16, 25];
                element.ignited = false;
                element.color = "yellow";
                element.igniteID = -1;
                if (array1.includes(index)) {
                    element.color = "aqua";
                } else if (array2.includes(index)) {
                    element.color = "magenta";
                }
            }
        });
        for (let i = 0; i < 3; i++) {
            if (!players[currentPlayer].spells[i]) {
                document.getElementById("ability" + (i + 1).toString()).style.backgroundColor = "red";
                document.getElementById("ability" + (i + 1).toString()).classList.remove("zoom");
            } else {
                document.getElementById("ability" + (i + 1).toString()).style.backgroundColor = "green";
                document.getElementById("ability" + (i + 1).toString()).classList.add("zoom");
            }
        }
        inAnimation = false;
    }
}

function animateToNextField(amount) {
    var currentField = game[players[currentPlayer].position];
    var nextField;
    if (amount > 0) {
        nextField = game[players[currentPlayer].position + 1];
        amount--;
    } else if (amount < 0) {
        nextField = game[players[currentPlayer].position - 1];
        amount++;
    } else {
        if (!nextplayer) {
            endStep();
        }
        return;
    }
    var direction = [];
    direction[0] = nextField.x - currentField.x;
    direction[1] = nextField.y - currentField.y;
    direction[0] /= 60;
    direction[1] /= 60;
    var count = 0;
    var timer = setInterval(function () {
        players[currentPlayer].x += direction[0] * 2;
        players[currentPlayer].y += direction[1] * 2;
        redraw();
        if (++count == 30) {
            clearInterval(timer);
            players[currentPlayer].setField(nextField);
            setTimeout(animateToNextField, 120, amount);
        }
    }, 16, direction, nextField);
}

function dice() {
    inAnimation = true;
    random = Math.floor(Math.random() * 6 + 1);
    document.getElementById("dice").src = "img/dice" + random + ".png";
    if (doubleBuff) {
        random *= 2;
        doubleBuff = false;
    }
    if (igniteBuff) {
        igniteBuff = false;
        var a = players[currentPlayer].position;
        var b = players[currentPlayer].position + random;
        for (var i = a + 1; i < b; i++) {
            game[i].ignited = true;
            game[i].color = "red";
            game[i].igniteID = currentPlayer;
        }
        redraw();
    }
    if (frostBuff) {
        frostBuff = false;
        var a = 0;
        players.forEach((element, index, array) => {
            if (element.position > players[a].position) a = index;
        });
        players[a].skipTurn = true;
    }
    for (var i = 0; i < 3; i++) {
        if (players[currentPlayer].spellsTemporary[i])
            players[currentPlayer].spells[i] = false;
    }
    nextStep(random);
}

function spell(x) {
    players[currentPlayer].spell(x)
}

function winner(x) {
    document.getElementById("winnerColor").src = "img/" + x + ".png";
    switch (x) {
        case "green":
            document.getElementById("winnerText").innerHTML = "A zöld játékos nyert!";
            break;
        case "red":
            document.getElementById("winnerText").innerHTML = "A piros játékos nyert!";
            break;
        case "blue":
            document.getElementById("winnerText").innerHTML = "A kék játékos nyert!";
            break;
        case "yellow":
            document.getElementById("winnerText").innerHTML = "A sárga játékos nyert!";
            break;
        default:
            document.getElementById("winnerText").innerHTML = "A játékos nyert!";
    }
    document.getElementById("winnerText");
    $('#exampleModalCenter').modal('show')

}