const isTrue = (currentValue) => currentValue[0] == true;



function generate_perso_level() {

    var isEtNonAllowed = false;
    var isOuNonAllowed = false;
    var isNotAllowed = false;
    var isOuAllowed = false;
    timeEnd = 25;
    double = false;
    isTuto = false;

    createStage("play_container");
    stage.add(layer);
    var logiqueCount = 0;
    for (let i = 0; i < colonneTot; i++) {
        liveColonneNumber.push([]);
    }
    for (let i = 0; i < colonneTot; i++) {
        for (let j = 0; j < numberPerColonne[i]; j++) {
            logiqueCount++;
            let numberRandom = getRandomArbitrary(0, arrayPorte.length);
            insertLogiqueColonne("logique" + logiqueCount, arrayPorte[numberRandom][1], i);
        }
    }


    logiques.forEach(function (element) {
        createLinkAuto(element.name);
    });
    initEndGame();

    timer.stop();
}



function loadPerso() {

    arrayPorte = [
        [document.querySelector("#logique1").checked, "et"],
        [document.querySelector("#logique2").checked, "ou"],
        [document.querySelector("#logique3").checked, "inv"],
        [document.querySelector("#logique4").checked, "etnon"],
        [document.querySelector("#logique5").checked, "nonou"]
    ];
    document.querySelector("#PersoSetupPage").style.display = 'none';
    document.querySelector("#playPage").style.display = 'block';
    resetAllTabs(false);
    niveauActuel = 1;
    timeTot = 0;
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    if (document.querySelector("#colonne_number_setup").value == 0) {
        var porteTotal = parseInt(document.querySelector("#colonne_number_setup_global").value);
        colonneTot = 0;
        while (porteTotal > 2) {
            porteTotal = porteTotal / 2;
            numberPerColonne.push(porteTotal);
            colonneTot++;
        }
        numberPerColonne.push(porteTotal);
        colonneTot++;

    } else {
        colonneTot = parseInt(document.querySelector("#colonne_number_setup").value);
        document.querySelectorAll(".input_refresh").forEach(function (element) {
            numberPerColonne.push(parseInt(element.value));
        });
    }
    arrayPorte = arrayPorte.filter(function (e) {
        if (e[0] === true) return e;
    })
    generate_perso_level();
    isLineCollapsing()
    click = 0;
    let i = 0;
    var error = false;
    while (checkIfEnd()) {
        if (i === NOMBRETEST) {
            error = true;
            break;
        }
        resetAllTabs(false);
        generate_perso_level();
        isLineCollapsing();
        i++;
    }
    if (error) {
        document.location.reload(true);
    }

}

function spin(button) {
    button.childNodes[3].classList = "fa fa-spinner";
}

function stopspin(button) {
    button.childNodes[3].classList = "fa fa-arrow-right";
}

function buttonSpin(button) {
    spin(document.querySelector("#generate_button_perso"));
    setTimeout(loadPerso, 1000);
}

function tuto(niveau) {
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    var numberColonne1 = 2;
    var numberColonne2 = 1;
    var isEtNonAllowed = false;
    var isOuNonAllowed = false;
    var isNotAllowed = false;
    var isOuAllowed = false;
    var finish = false;
    var firstTime = [];
    switch (niveauActuel) {
        case 1:
            firstTime.push("et");
            break;
        case 2:
            firstTime.push("inv");
            break;
        case 3:
            firstTime.push("ou");
            break;
        case 4:
            firstTime.push("nand");
            break;
        case 5:
            firstTime.push("nonou");
            break;
        default:
            finish = true;
            break;
    }
    isTuto = false;
    createStage("play_container");
    stage.add(layer);
    colonneTot = 3;
    numberPerColonne = [numberColonne1, numberColonne2, 2];
    var logiqueCount = 0;

    if (firstTime.length > 0) {
        numberColonne1 = 1;
        numberColonne2 = 0;
        numberPerColonne = [numberColonne1, numberColonne2];
        liveColonneNumber.push([]);
        timeEnd = 20;
        insertLogiqueColonne("logique" + logiqueCount, firstTime[0], 0);
        if (allowedInfoPorte) {
            openModal('firstTime' + firstTime[0]);
            timer.pause();
        }
    }
    logiques.forEach(function (element) {
        createLinkAuto(element.name);
    });
    initEndGame("tuto");
}


function createGameOne(niveau) {
    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;
    var numberColonne1 = 2;
    var numberColonne2 = 1;
    var isEtNonAllowed = false;
    var isOuNonAllowed = false;
    var isNotAllowed = false;
    var isOuAllowed = false;
    double = false;
    var firstTime = [];
    switch (niveauActuel) {
        case 1:
            firstTime.push("et");
            break;
        case 2:
            numberColonne1 = 2;
            numberColonne2 = 0;
            timeEnd = 15;
            break;
        case 3:
            numberColonne1 = 2;
            numberColonne2 = 1;
            timeEnd = 15;
            break;
        case 4:
            numberColonne1 = 3;
            numberColonne2 = 1;
            timeEnd = 20;
            break;
            //Fin premiere serie
        case 5:
            firstTime.push("inv");
            isNotAllowed = true;
            timeEnd = 20;
            break;
        case 6:
            numberColonne1 = 2;
            numberColonne2 = 0;
            isNotAllowed = true;
            timeEnd = 20;
            break;
        case 7:
            numberColonne1 = 2;
            numberColonne2 = 1;
            isNotAllowed = true;
            timeEnd = 20;
            break;
        case 8:
            numberColonne1 = 3;
            numberColonne2 = 1;
            isNotAllowed = true;
            timeEnd = 20;
            break;
        case 9:
            numberColonne1 = 4;
            numberColonne2 = 2;
            isNotAllowed = true;
            double = true;
            timeEnd = 25;
            break;
        case 10:
            firstTime.push("ou");
            break;
        case 11:
            isNotAllowed = true;
            isOuAllowed = true;
            numberColonne1 = 3;
            numberColonne2 = 1;
            timeEnd = 20;
            break;
        case 12:
        case 13:
        case 14:
            isNotAllowed = true;
            isOuAllowed = true;
            numberColonne1 = 3;
            numberColonne2 = 1;
            timeEnd = 20;
            break;
        default:
            isEtNonAllowed = true;
            isOuNonAllowed = true;
            timeEnd = 20;
            numberColonne1 = 4;
            numberColonne2 = 4;
            break;
    }
    isTuto = false;
    createStage("play_container");
    stage.add(layer);
    colonneTot = 3;
    numberPerColonne = [numberColonne1, numberColonne2, 2];
    var logiqueCount = 0;

    if (firstTime.length > 0) {
        numberColonne1 = 1;
        numberColonne2 = 0;
        numberPerColonne = [numberColonne1, numberColonne2];
        liveColonneNumber.push([]);
        timeEnd = 20;
        insertLogiqueColonne("logique" + logiqueCount, firstTime[0], 0);
        if (allowedInfoPorte) {
            openModal('firstTime' + firstTime[0]);
            timer.pause();
        }
    } else {
        for (let i = 0; i < colonneTot; i++) {
            liveColonneNumber.push([]);
        }
        for (let i = 0; i < colonneTot; i++) {
            for (let j = 0; j < numberPerColonne[i]; j++) {
                logiqueCount++;
                let type = null;
                let x = 1;
                if (isOuAllowed) x++;
                if (isEtNonAllowed) x++;
                if (isOuNonAllowed) x++;
                if (isNotAllowed) x++;
                let numberRandom = getRandomArbitrary(0, x);
                switch (numberRandom) {
                    case 0:
                        type = "et";
                        break;
                    case 1:
                        type = "inv";
                        break;
                    case 2:
                        type = "ou";
                        break;
                    case 3:
                        type = "etnon";
                        break;
                    case 4:
                        type = "nonou";
                        break;
                }
                insertLogiqueColonne("logique" + logiqueCount, type, i);
            }
        }
    }

    logiques.forEach(function (element) {
        createLinkAuto(element.name);
    });
    initEndGame();
}


function generate2() {
    var matchs = [
        [3, 2],
        [2, 2]
    ];
    var fork = [
        [2, 1],
        [1, 1]
    ];

    var numberCol = 3;
    var numberPerCol = [5, 3, 2];

    colonneTot = 3;
    numberPerColonne = [5, 3, 2];
    var compt = new Array();
    var listeSame = [];
    let num = 1;

    //attribution
    for (let i = numberCol; i > 0; i--) {

        matchs.forEach(function (element) {
            if (element[0] == i) {
                for (let j = 0; j < element[1]; j++) {
                    compt.push([i, "same" + num]);
                    numberPerCol[i - 1]--;
                    listeSame.push(["same" + num, null]);
                }
                num++;
            }
        });
        for (let j = 0; j < numberPerCol[i - 1]; j++)
            compt.push([i, "normal"]);
    }

    //creation et lien
    var listeLogiqueObj = new Array();
    let i = 0;
    compt.forEach(function (element) {
        if (element[1] === "normal") {
            listeLogiqueObj.push({
                id: "logique" + i,
                col: element[0],
                id1: null,
                id2: null,
                id3: null,
                matchId1: null,
                type: null,
            });
        } else {
            listeLogiqueObj.push({
                id: "logique" + i,
                col: element[0],
                id1: null,
                id2: null,
                id3: null,
                matchId1: element[1],
                type: null,
            });
        }
        i++;
    });
    //Attribution des types
    //num = liste de comptatibilité

    let num2 = getRandomArbitrary(0, 3);
    for (x in compt) {
        if (listeLogiqueObj[x].matchId1 !== null) {
            if (getElementArray(listeLogiqueObj[x].matchId1, listeSame)[1] === null) {
                getElementArray(listeLogiqueObj[x].matchId1, listeSame)[1] = num2;
                num2 = getRandomArbitrary(0, 3);
            } else {
                listeSame[x] = getElementArray(listeLogiqueObj[x].matchId1, listeSame);
            }
        }
    }
    createStage("play_container");
    stage.add(layer);
    timeEnd = 1000;

    for (let i = 0; i < colonneTot; i++) {
        liveColonneNumber.push([]);
    }
    initTimer();
    //creation logique
    listeLogiqueObj.forEach(function (logique) {
        if (getTypeFromSameMatch(listeSame, logique.matchId1) === null) logique.type = getRandomArbitrary(0, 3);
        else logique.type = getTypeFromSameMatch(listeSame, logique.matchId1);
        switch (logique.type) {
            case 0:
                insertLogiqueColonne(logique.id, "et", logique.col - 1);
                break;
            case 1:
                insertLogiqueColonne(logique.id, "ou", logique.col - 1);
                break;
            case 2:
                insertLogiqueColonne(logique.id, "inv", logique.col - 1);
                break;
        }
    });
    var logiques;
    //creation de liens entre les portes logiques :
    for (let col = 1; col < colonneTot; col++) {
        //recuperer tout les logiques :
        logiques = new Array();
        listeLogiqueObj.forEach(function (logique) {
            if (logique.col === col && logique.id3 === null) logiques.push(logique);
        });
        //check si y a des fork
        while (getNumberFork(fork, col) > 0) {
            fork.forEach(function (element) {
                if (element[0] === col) {
                    //selection de la sortie a forker :
                    let logiqueFork = logiques[getRandomArbitrary(0, logiques.length)];
                    //recupération des logiques d'entree :
                    let logiqueEntre = new Array();
                    let sameId = null;
                    listeLogiqueObj.forEach(function (logique) {

                        if (logique.col === col + 1) {
                            if (sameId === null) {
                                sameId = logique.matchId1;
                                logiqueEntre.push(logique);
                            } else if (sameId === logique.matchId1)
                                logiqueEntre.push(logique);
                        }
                    });
                    logiqueFork.id3 = "done";
                    //creation du lien avec fork :
                    for (let i = 0; i < logiqueEntre.length; i++) {
                        createLink(findLogique(logiqueFork.id), findLogique(logiqueEntre[i].id));
                    }

                    fork.splice(fork.indexOf(element), 1);
                }
            });

        }

    }
    //creation des autres liens :
    //recupération des logiques restants :
    for (x in listeLogiqueObj) {
        if (listeLogiqueObj[x].id3 === null && listeLogiqueObj[x].col !== colonneTot) {
            //liste des logiques possible :
            let loqiques = new Array();
            listeLogiqueObj.forEach(function (logique) {
                if (logique.col === listeLogiqueObj[x].col + 1) {
                    if (logique.type === 2 && checkLogiqueLines(logique.id, "id1") === null) logiques.push(logique);
                    else if (logique.type !== 2) {
                        if (checkLogiqueLines(logique.id, "id1") === null || checkLogiqueLines(logique.id, "id2") === null) logiques.push(logique);
                    }
                }
            });
            //attribution du logique le plus proche :
            let logiqueFinal = null;
            logiques.forEach(function (logique) {
                if (logiqueFinal === null) {
                    logiqueFinal = logique;
                } else if (Math.abs(findLogique(listeLogiqueObj[x].id).y - findLogique(logique.id).y) < Math.abs(findLogique(listeLogiqueObj[x].id).y - findLogique(logiqueFinal.id).y)) {
                    logiqueFinal = logique;
                }
            });
            //console.log(listeLogiqueObj[x].id + " => " + logiqueFinal.id);
            console.log(findLogique(listeLogiqueObj[x].id));
            createLink(findLogique(listeLogiqueObj[x].id), findLogique(logiqueFinal.id));
        }
    }
}

function getNumberFork(arr, col) {
    let num = 0;
    arr.forEach(function (item) {
        if (item[0] === col) num++;
    });
    return num;
}

function getElementArray(one, array) {
    retour = null;
    array.forEach(function (element) {
        if (element[0] === one && retour === null) {
            retour = element;
        }
    });
    return retour;
}

function getTypeFromSameMatch(listeMatch, sameId) {
    retour = null;
    listeMatch.forEach(function (element) {
        if (element[0] === sameId)
            retour = element[1];
    });
    return retour;
}


//a l'epoque
function generateFromBottom() {
    var NombrecolonneTest = 2;
    var numberPerColonneTest = [3, 2];
    var porteBool = [
        [true, "et"],
        [true, "ou"],
        [true, "inv"]
    ];
    var logiquesTest = [];

    for (let i = NombrecolonneTest; i > 0; i--) {
        for (let j = 0; j < numberPerColonneTest[i - 1]; j++) {
            let numberRandom = getRandomArbitrary(0, porteBool.length);
            logiquesTest.push([porteBool[numberRandom][1], i, j, (j + 1) * 10]);

        }
    }
    createLink(logiquesTest, numberPerColonneTest[numberPerColonneTest.length - 1]);
}

function createLinkTest(listeLogique, colonneMax) {
    listeLogique.forEach(function (element) {
        if (element[1] !== colonneMax) {
            console.log(element);
            listeLogique.forEach(function (item) {
                if (item[1] !== colonneMax) {
                    console.log(item);
                }
            });
        }
    });
}

function isValid(listeLogique, colonneMax) {
    listeLogique.forEach(function (element) {
        //derniere colonne donc fin
        if (element[1] == colonneMax) {
            console.log(element);
        }
    });
}