import {bordersShown, games, invertBorder, IsImgsDisplayed, Move, showBorders, switchToGraph} from "./index";
import {addColumnLeft, addColumnRight, addRowAbove, addRowUnder, clearBoard, resizeBoard} from "./Board";

let min_x = 0;
let max_x = 0;
let min_y = 0;
let max_y = 0;
let gameIndex = 0;
let gameMoveId = 0;

const playerColors = ["blue", "yellow", "purple"];

function resetVar() {
    min_y = 0;
    min_x = 0;
    max_x = 0;
    max_y = 0;
    gameMoveId = 0;
}

/**
 *  change the displayed game info to the previous/next game
 */
function switchPrevGame() {
    clearBoard();
    if (gameIndex > 0)
        gameIndex--;
    //setGameInfo();
    (<HTMLElement>document.getElementById("gameIDdisp")).innerText = gameIndex + "";
    setTimeout(setGameInfo, 1); // prevent the big flash before the board is fully resized
}

function switchNextGame() {
    clearBoard();
    if (gameIndex < games.length - 1)
        gameIndex++;
    setTimeout(setGameInfo, 1);
    (<HTMLElement>document.getElementById("gameIDdisp")).innerText = gameIndex + "";
    //setGameInfo();
}

/**
 * change game info value to gameIndex game
 */
function setGameInfo() {
    (<HTMLElement>document.getElementById("seed_disp")).innerText = games[gameIndex].seed + "";
    (<HTMLElement>document.getElementById("player0_disp")).innerText = games[gameIndex].player0 + "";
    (<HTMLElement>document.getElementById("player1_disp")).innerText = games[gameIndex].player1 + "";
    (<HTMLElement>document.getElementById("winner_disp")).innerText = games[gameIndex].winner + "";
    (<HTMLElement>document.getElementById("cause_disp")).innerText = games[gameIndex].cause + "";
    addMove(games[gameIndex]["moves"][0]);
    gameMoveId = 0;
}

function nextMove() {
    if (games[gameIndex]["moves"][gameMoveId + 1] !== undefined) {
        gameMoveId++;
        addMove(games[gameIndex]["moves"][gameMoveId]);
    }

}

function prevMove() {
    if (gameMoveId > 0) {
        removeMove(games[gameIndex]["moves"][gameMoveId]);
        gameMoveId--;
    }

}

function tolastMove() {
    while (games[gameIndex]["moves"][gameMoveId + 1] !== undefined) {
        nextMove();
    }
}

function toFirstMove() {
    while (gameMoveId > 0) {
        prevMove();
    }
}

/**
 * returns if 0 x is in intervall [a, b], a and b included, -1 if x < a, 1 if x > b
 * @param x
 * @param a
 * @param b
 */
function inInterval(x: number, a: number, b: number) {
    return x < a ? -1 : x > b ? 1 : 0;
}

/**
 * resize the board and add the move to it
 * @param move
 */
function addMove(move: Move) {
    switch (inInterval(move.x, min_x, max_x)) {
        case 0:
            break;
        case 1:
            max_x++;
            addColumnRight();
            break;
        case -1:
            min_x--;
            addColumnLeft();
            break;
    }
    switch (inInterval(-move.y, min_y, max_y)) {
        case 0:
            break;
        case 1:
            max_y++;
            addRowUnder();
            break;
        case -1:
            min_y--;
            addRowAbove();
            break;
    }
    placeMove(move);
}

function resideBoardScreenSize() {
    const nb_lines = (window.innerHeight - 200) / 200;
    const nb_cols = (window.innerWidth - 200) / 200;
    let side = false;
    for (let i = 0; i < nb_lines; i++) {
        if (side) {
            max_y++;
            addRowUnder();
            side = !side;
        } else {
            side = !side;
            min_y--;
            addRowAbove();
        }
    }

    for (let i = 0; i < nb_cols; i++) {
        if (side) {
            side = !side;
            max_x++;
            addColumnRight();
        } else {
            side = !side;
            min_x--;
            addColumnLeft();
        }
    }

}

function setInnerTile(elm: HTMLElement, tile: number[], angle: string) {

    const idx_to_cord = [[1, 0], [2, 0], [3, 0], [4, 1], [4, 2], [4, 3], [3, 4], [2, 4], [1, 4], [0, 3], [0, 2], [0, 1], [2, 2]];
    const nb_to_color = ["green", "gray", "blue", "#964B00", "purple", "gold", "#069AF3", "#420D08", "white", "none"];
    elm.children[0].children[0].innerHTML = gameMoveId + "";
    if (tile[0] !== 9)
        (<HTMLElement>elm.children[0].children[0]).style.opacity = "1";
    else
        (<HTMLElement>elm.children[0].children[0]).style.opacity = "0";
    // console.log("Adding a new " + (IsImgsDisplayed ? "HIDDEN" : "VISIBLE") + " graph tile");
    for (let i = 0; i < 13; i++) {
        const subLine = elm.children[idx_to_cord[i][1]];
        (<HTMLElement>subLine.children[idx_to_cord[i][0]]).style.background = nb_to_color[tile[i]];
        if (IsImgsDisplayed)
            (<HTMLElement>subLine.children[idx_to_cord[i][0]]).classList.add("hidden");
    }
}

/**
 * there is thesubTiledding part
 * @param move
 */
function placeMove(move: Move) {
    const line = <HTMLElement>document.getElementById("line" + (-move.y - min_y));
    const box = <HTMLElement>line.children[move.x - min_x];
    box.classList.add("player" + move.id + (bordersShown ? "" : "-hidden"));
    const img = document.createElement("img");
    img.src = './imgs/' + move.tile.name + ".jpg";
    img.className = "tileImg";
    if (!IsImgsDisplayed)
        img.className += " hidden";
    box.append(img);
    img.style.rotate = '-' + move.tile.angle + "deg";
    setInnerTile(box, move.tile.c, move.tile.angle);

}


function removeMove(move: Move) {
    const line = <HTMLElement>document.getElementById("line" + (-move.y - min_y));
    const box = <HTMLElement>line.children[move.x - min_x];
    setInnerTile(box, Array(13).fill(9), "0");
    box.removeChild(box.getElementsByTagName('img')[0]);
    box.style.border = "none";
    box.style.rotate = "0";

}

const prevGameButton = (<HTMLElement>document.getElementById("prevGameButton"));
const nextGameButton = (<HTMLElement>document.getElementById("nextGameButton"));

const nextMoveButton = (<HTMLElement>document.getElementById("nextMoveButton"));
const prevMoveButton = (<HTMLElement>document.getElementById("prevMoveButton"));

const lastMoveButton = (<HTMLElement>document.getElementById("lastMoveButton"));
const firstMoveButton = (<HTMLElement>document.getElementById("firstMoveButton"));

prevGameButton.addEventListener("click", switchPrevGame);
nextGameButton.addEventListener("click", switchNextGame);

nextMoveButton.addEventListener("click", nextMove);
prevMoveButton.addEventListener("click", prevMove);

lastMoveButton.addEventListener("click", tolastMove);
firstMoveButton.addEventListener("click", toFirstMove);

function keyShortcut(e: { keyCode: number, ctrlKey: boolean, shiftKey: boolean }) {
    // console.log(`key ${e.keyCode} pressed`);
    switch (e.keyCode) {
        case 37:
            if (e.shiftKey) {
                toFirstMove();
                break;
            }
            if (e.ctrlKey) {
                switchPrevGame();
                break;
            }
            prevMove();
            break;
        case 39:
            if (e.shiftKey) {
                tolastMove();
                break;
            }
            if (e.ctrlKey) {
                switchNextGame();
                break;
            }
            nextMove();
            break;
        case 71:
            switchToGraph();
            break;
        case 84:
            invertBorder();
            break;
    }
}


document.addEventListener("keydown", keyShortcut);

export {setGameInfo, switchPrevGame, resetVar, resideBoardScreenSize};




