
var canvasT = document.getElementById('canvasTotal');
var ctxT = canvasT.getContext('2d');

var canvasO = document.getElementById('canvasObj');
var ctxO = canvasO.getContext('2d');

var canvasR = document.getElementById('canvasR');
//var ctxR = canvasR.getContext('2d');

tab1=[];
tab2=[];
tab3=[];
tab4=[];

tabR=[[],[],[],[],[]];

tabR1=[];
tabR2=[];
tabR3=[];
tabR4=[];

points=0;
tabTotal=[];
tabObjCmp=[];
mousePos=[];

var pause=getCookie("pause");

var displayType = getCookie("displayMode")=="" ? "gems" : getCookie("displayMode");

var dotsAmount= getCookie("dotsAmount")=="" ? 4 : getCookie("dotsAmount");
var colors=[];
var colorsAvailable=["red","yellow","green","purple","black","brown","cyan","orange"];
var customColorsAvailable=[];

for(var cpt=1;cpt<9;cpt++)
{
    customColorsAvailable.push((getCookie("color_"+cpt)=="" ? colorsAvailable[cpt-1] : getCookie("color_"+cpt)));
}

var gemsAvailable=["red","yellow","green","purple","black","brown","cyan","orange"];
var gemsSelected=[];

for(var cpt=0;cpt<8;cpt++)
{
  gemsSelected[cpt]= (getCookie("gem"+(cpt+1))=="" ? gemsAvailable[cpt] : getCookie("gem"+(cpt+1)));
}

for(var cpt=0;cpt<dotsAmount;cpt++)
{
    if(displayType=="points")
    {
        colors.push(customColorsAvailable[cpt]+"_"+cpt);
    }
    else
    {
        colors.push(gemsSelected[cpt]+"_"+cpt);
    }
}

size=screen.height/6; // 6 lignes de 50px // 6 colonnes de 50x
canvasT.width=size;
canvasO.width=size;

canvasT.height=size;
canvasO.height=size;

document.getElementById("btn_back").width=size;

for(var a=1;a<5;a++)
{
    eval("var canvas"+ a +"= document.getElementById('canvas"+a+"')");
    eval("var ctx"+a+" = canvas"+a+".getContext('2d')");
    eval("canvas"+a+".width=size");
    eval("canvas"+a+".height=size");
    
    eval("var canvasR"+ a +"= document.getElementById('canvasR"+a+"')");
    eval("var ctxR"+a+" = canvasR"+a+".getContext('2d')");
    eval("canvasR"+a+".width=size");
    eval("canvasR"+a+".height=size");
}

function faireCercle(x,y,color,lectx){
    var cercle = new Path2D();
    
    nx=(size/6)*(x>0 ? x+2 : x+3);
    ny=(size/6)*(y>0 ? y+2 : y+3);
    
    cercle.moveTo(nx, ny);
    cercle.arc(nx+(size/12), ny+(size/12), (size/12), 0, 2 * Math.PI);
    
    lectx.fillStyle = color.substring(0, color.length-2);
    lectx.fill(cercle);
}

function drawImg(x,y,color,lectx)
{
    var img= new Image();
    
    
    var nx=(size/6)*(x>0 ? x+2 : x+3);
    var ny=(size/6)*(y>0 ? y+2 : y+3);
    
    img.src="ress/"+color.substring(0, color.length-2)+".png";
    
    img.onload = function(){
        if(displayType=="gems")
        {
            lectx.drawImage(img,nx,ny,size/6,size/6); 
        }
        else
        {
            lectx.drawImage(img,nx+(size/48),ny+(size/48),size/8,size/8);  
        }
    }
    
}

function genVitraux()
{
    var mat = matrix(6,6);
    var x;
    var y;
    var baseVitrail=[];
    var tries;

    for(var cpt=0;cpt<dotsAmount;cpt++)
    {
        x=getRandomInt(6)-1;
        y=getRandomInt(6)-1;

        while(mat[x][y]!=0 && tries!=20)
        {
            x=getRandomInt(6)-1;
            y=getRandomInt(6)-1;

            tries++;
        }

        mat[x][y]=1;
        x-=2;
        y-=2;
        baseVitrail.push([(x>0 ? x : x-1),(y>0 ? y : y-1),colors[cpt]]);
        tries=0;
    }
    
    for(var i=1;i<5;i++)
    {
        eval("tab"+i+"=copyMDArray(baseVitrail)");
        eval("tab"+i+".unshift(true)");
    }
}

function tourneG(letab,lecanvas,lectx,sselem=null)
{
    
    if(sselem==null){
        letab.forEach(element => {
            tmp=element[0];
            element[0]=element[1];
            element[1]=-tmp;
        });
    }
    
    else {
        letab[sselem].forEach(element => {
            tmp=element[1];
            element[1]=element[0];
            element[0]=-tmp;
        });
    }
    //console.log("pre-empiler :"+tabTotal);
    empiler(sselem!=null);
    //console.log("post-empiler :"+tabTotal);
    if(sselem==null)
    toutDessiner(letab,lecanvas,lectx);
}

function tourneD(letab,lecanvas,lectx,sselem=null)
{
    if(sselem==null){
        letab.forEach(element => {
            tmp=element[1];
            element[1]=element[0];
            element[0]=-tmp;
        });
    }
    
    else {
        letab[sselem].forEach(element => {
            tmp=element[1];
            element[1]=element[0];
            element[0]=-tmp;
        });
    }
    //console.log("pre-empiler :"+tabTotal);
    empiler(sselem!=null);
    //console.log("post-empiler :"+tabTotal);
    if(sselem==null)
    toutDessiner(letab,lecanvas,lectx);
}

function toutDessiner(pts,lecanvas,lectx)
{
    lectx.clearRect(0, 0, lecanvas.width, lecanvas.height);
    if(pts[0])
    {
        var i=1*(typeof pts[0]==="boolean");
        for(i;i<pts.length;i++)
        {
            if(Array.isArray(pts[i]))
            {
                if(displayType=="points" || displayType=="both")
                    faireCercle(pts[i][0],pts[i][1],pts[i][2],lectx);
                if(displayType=="gems" || displayType=="both")
                    drawImg(pts[i][0],pts[i][1],pts[i][2],lectx);
            }
        }
    }
}

function empiler(obj=false)
{
    const unique = (val) => val.toString() != test.toString();
    var exists=false;
    
    if(!obj)
    {
        tabTotal=[];
        if(tab1[0])
        {
            tab1.forEach(element => {
                if(Array.isArray(element) && element.length!=0)
                {
                    tabTotal.push(element);
                }
            })
        }
        if(tab2[0]){
            
            tab2.forEach(element => {
                if(Array.isArray(element) && element.length!=0)
                {
                    colors.forEach(col => {
                        test=[element[0],element[1],col];
                        if(!exists)
                        exists=!tabTotal.every(unique);
                    })
                    if(!exists)
                    tabTotal.push(element);
                    //console.log("tabtotal tab2 "+tabTotal+"|");
                    exists=false;
                }
            })
        }
        if(tab3[0])
        {
            
            tab3.forEach(element => {
                if(Array.isArray(element) && element.length!=0){
                    colors.forEach(col => {
                        test=[element[0],element[1],col];
                        if(!exists)
                        exists=!tabTotal.every(unique);
                    })
                    if(!exists)
                    tabTotal.push(element);
                    exists=false;
                }
            })
        }
        if(tab4[0]){
            
            tab4.forEach(element => {
                if(Array.isArray(element) && element.length!=0)
                {
                    colors.forEach(col => {
                        test=[element[0],element[1],col];
                        if(!exists)
                        exists=!tabTotal.every(unique);
                    })
                    if(!exists)
                    tabTotal.push(element);
                    exists=false;
                }
            })
        }
        checkAllOK();
        toutDessiner(tabTotal,canvasT,ctxT);
    }
    else{
        tabObjCmp=[];
        for(count=1;count<tabObj[0].length;count++)
        {
            tabObjCmp.push(tabObj[0][count]);
        }
        for(tabCount=1;tabCount<tabObj.length;tabCount++)
        {
            for(elmCount=1;elmCount<tabObj[tabCount].length;elmCount++)
            {
                element=tabObj[tabCount][elmCount];
                colors.forEach(col => {
                    test=[element[0],element[1],col];
                    if(!exists)
                    exists=!tabObjCmp.every(unique);
                })
                if(!exists)
                tabObjCmp.push(element);
                exists=false; 
            }
        }
    }
}

function swap(letab, lecanvas, lectx,ladir){
    if(ladir=="H"){
        letab.forEach(element=> {
            element[1]=-element[1];
        })
    }
    else {
        letab.forEach(element=> {
            element[0]=-element[0];
        })
    }
    if(lecanvas!=null)
    {
        
        toutDessiner(letab,lecanvas,lectx);
        empiler();
    }
}

function getRandomInt(max) { //rng entier [1;max]
    return Math.floor(Math.random() * Math.floor(max))+1;
}

function copyMDArray(array) //permet la copie d'arrays sans copier les références
{
    var newArray = [];
    array.forEach(element => {
        newArray.push(Array.from(element))
    });
    return newArray
}

function generate(){
    tabObj=[copyMDArray(tab1),copyMDArray(tab2),copyMDArray(tab3),copyMDArray(tab4)];
    tabObjCmp=[];
    var actions=getRandomInt(4)+1;
    var swapTreshold=11;
    var switchTreshold=11;
    if(difficulty=="med") //70% tournerD, 30% swap
    {
        actions+=getRandomInt(3)+3;
        swapTreshold=8;
    }
    if(difficulty=="hard") //50% tournerD, 30% swap, 20% switch
    {
        actions+=getRandomInt(5)+5;
        swapTreshold=6;
        switchTreshold=9;
    }
    
    console.log("actions : "+actions+" difficulty="+difficulty);
    
    while(actions>0){
        if(difficulty!="easy")
        act=getRandomInt(10);
        else
        act=1;
        //console.log("act="+act+" left:"+actions);
        if(switchTreshold<=act && actions>3) // faire un switch
        {
            var from=getRandomInt(4)-1;
            var to=getRandomInt(4)-1;
            while(from==to)
            to=getRandomInt(4)-1;
            
            [tabObj[from],tabObj[to]]=[tabObj[to],tabObj[from]];
            //console.log("switch "+from+"->"+to);
            actions-=3;
        }
        else if(swapTreshold<=act && actions>2)
        {
            var from=getRandomInt(4)-1;
            var dir=getRandomInt(2)==1 ? "H":"V";
            swap(tabObj[from],null,ctxO,dir);
            //console.log("swap"+dir+" de "+from);
            actions-=2;
        }
        else
        {
            tourneD(tabObj,canvasO,ctxO,getRandomInt(4)-1);
            actions-=1;
        }
    }
    empiler(true);
    if(checkAllOK(true)==true)
    {
        generate();
    }
    toutDessiner(tabObjCmp,canvasO,ctxO);
    
}

function getMousePosition(lecanvas, event, lectx, letab) { 
    let rect = lecanvas.getBoundingClientRect(); 
    let x = event.clientX - rect.left; 
    let y = event.clientY - rect.top; 
    let dir = compas(x,y,lecanvas);
    
    if(x<lecanvas.width/2)
    tourneG(letab,lecanvas,lectx);
    else
    tourneD(letab,lecanvas,lectx);
} 

/// renvoie le point cardianl où se trouve le point

function compas(x,y,lecanvas)
{
    rect = lecanvas.getBoundingClientRect(); 
    x = event.clientX - rect.left; 
    y = event.clientY - rect.top; 
    ne = x>y;
    se = x>lecanvas.height-y;
    
    if(ne && se ) return "E";
    if(ne && !se ) return "N";
    if(!ne && se ) return "S";
    if(!ne && !se ) return "O";
}


function rotationManager(e)
{
    var mouseOnRes = mousePos[0].match(/[R]/g)!=null;
    canvasNumber=e.currentTarget.id.substring(6);
    document.getElementById("canvas"+mousePos[0]).classList.remove('vitrail-select');
    
    console.log(mousePos[0]+" vers "+canvasNumber+", mouseOnRes?"+mouseOnRes);
    
    var firstAv=1;
    for(i=1;i<4;i++) //détermine la 1° place libre dans la réserve
    {
        if(typeof tabR[i][0]=="boolean")
        firstAv++;
        else
        break;
    }
    
    if(mouseOnRes && !canvasNumber.includes("R")) //clic dans la réserve, relâche sur la pile en jeu
    {
        if(!isVisible(canvasNumber)) //relâche sur emplacement vide au centre
        {
            toggleVisible(canvasNumber);
            tabR[canvasNumber]=[];
            //console.log("contenu du tabR[cn] : "+tabR[canvasNumber]);
            toggleVisible(mousePos[0].substring(1),true);
        }
    }
    else
    {
        if(isVisible(mousePos[0])) //clic sur un vitrail présent
        {
            if(canvasNumber.includes("R")) //relâche dans réserve
            {
                if(tabR[canvasNumber]==null) //emplacement de réserve vide
                {
                    toggleVisible(mousePos[0]); //inverser tag du canvas du centre
                    tabR[firstAv]=copyMDArray(eval("tab"+mousePos[0])); //mettre le canvas dans la réserve
                    tabR[firstAv][0]=eval("tab"+mousePos[0]+"[0]"); //transférer le tag du canvas dans la réserve
                    toggleVisible(firstAv,true); //inverser tag du canvas de réesrve
                    toutDessiner(tabR[firstAv],eval("canvasR"+firstAv),eval("ctxR"+firstAv)); //afficher canvas dans réserve
                    //console.log(eval("tabR["+(mousePos[0]-1)+"]"));
                }
                else //emplacement de réserve occupé
                {
                    changeOrder(mousePos[0],canvasNumber);
                }
            }
            else
            {
                lecanvas=eval("canvas"+canvasNumber);
                letab=eval("tab"+canvasNumber);
                lectx=lecanvas.getContext('2d');
                dir = compas(e.clientX,e.clientY,e.currentTarget);
                if(mousePos[0]==canvasNumber)
                {
                    if((mousePos[1]=="N" && dir == "O") || (mousePos[1]=="S" && dir == "E") || (mousePos[1]=="O" && dir == "S") || (mousePos[1]=="E" && dir == "N"))
                    {
                        tourneG(letab,lecanvas,lectx);
                    }
                    else if((mousePos[1] == "N" && dir == "E") || (mousePos[1] == "S" && dir == "O") || (mousePos[1] == "E" && dir == "S") || (mousePos[1] == "O" && dir == "N"))
                    {
                        tourneD(letab,lecanvas,lectx);
                    }
                    else if ((mousePos[1] == "E" && dir == "O") || (mousePos[1] == "O" && dir == "E"))
                    {
                        swap(letab,lecanvas,lectx,"V");
                    }
                    else if ((mousePos[1] == "N" && dir == "S") || (mousePos[1] == "S" && dir == "N"))
                    {
                        swap(letab,lecanvas,lectx,"H");
                    }
                }
                else
                {
                    changeOrder(mousePos[0],canvasNumber);
                }
            }
        }
    }
}


function checkAllOK(justChecking=false){
    //const condition = (val) => val.toString() == element.toString();
    var exists=true;
    //exists=!tabObjCmp.every(unique);
    if(tabTotal.length==tabObjCmp.length)
    {
        var verifTab=[];
        verifTab=copyMDArray(tabTotal);
        
        
        for(i=0;i<tabTotal.length;i++)
        {
            const result = verifTab.filter(point => point.toString()==tabObjCmp[i].toString());
            //console.log(verifTab.filter(point => point.toString()+" et "+tabObjCmp[i].toString()));
            exists*=result.length;
        }
    }
    else
    {
        exists=false;
    }
    
    if(!tutoMode)
    {
        if(exists && !justChecking)
        {
            var audio = new Audio('ress/Jewel4.mp3');
            audio.play();
            if(pause)
                chronoStop();
            handleScore(1);
            generate();
        }
        else if(justChecking)
        {
            return exists;
        }
    }
    else
    {
        if(points==0)
        {
            points=-1;
            console.log("points "+points);
        }
        if(exists)
        {
            handleTuto();
        }
        
    }
    
}

function handleScore(modif)
{
    points+=modif;
    document.getElementById("stats").innerHTML = points+" points";
    
    if(objPts!=null && points==objPts)
    {
        chronoStop();
        var pts = diff.getSeconds()+ (diff.getMinutes()*60) + ((diff.getHours()-1)*3600);
        //console.log("./score.php?pts="+pts+"&mode="+get['mode']+"&diff="+get['diff']+"&pseudo="+get['pseudo']);
        window.location.replace("./score.php?pts="+pts+"&mode="+get['mode']+"&diff="+get['diff']+"&pseudo="+get['pseudo']);
    }
    else if(get['mode']=="surv")
    {
        addTime(30);
    }
}

function changeOrder(from, to)
{
    if(from.includes("R"))
    fromTab=tabR[from];
    else
    fromTab=eval("tab"+from);
    
    if(to.includes("R"))
    toTab=tabR[to];
    else
    toTab=eval("tab"+to);
    
    for(i=0;i<toTab.length;i++)
    {
        
        [fromTab[i],toTab[i]]=[toTab[i],fromTab[i]];
    }
    //[fromTab,toTab]=[toTab,fromTab];
    toutDessiner(fromTab,eval("canvas"+from),eval("ctx"+from));
    toutDessiner(toTab,eval("canvas"+to),eval("ctx"+to));
    empiler();
    toutDessiner(tabTotal,canvasT,ctxT);
    
    
}

function isVisible(what)
{
    if(what.includes("R"))
    {
        if(tabR[what.substring(1)]==null)
        return null;
        return tabR[what.substring(1)][0];
    }
    
    return eval("tab"+what+"[0]");
}

function toggleVisible(where,reserve=false)
{
    if(!reserve)
    {
        eval("tab"+where+"[0]=!tab"+where+"[0];");
        empiler();
        toutDessiner(eval("tab"+where),eval("canvas"+where),eval("ctx"+where));
        toutDessiner(tabTotal,canvasT,ctxT);
    }
    else
    {
        tabR[where][0]=!tabR[where][0];
        toutDessiner(tabR[where],eval("canvasR"+where),eval("ctxR"+where));
    }
}

function matrix(m, n) {
    var result = []
    for(var i = 0; i < n; i++) {
        result.push(new Array(m).fill(0))
    }
    return result
}

function events() {
    for(var i=1;i<5;i++)
    {
        eval("canvas"+i).addEventListener("mousedown",function(e){mdManager(e);});
        eval("canvas"+i).addEventListener("mouseup",function(e){muManager(e);});
        eval("canvas"+i).addEventListener("mouseenter",function(e){meManager(e);});
        eval("canvas"+i).addEventListener("mouseleave",function(e){mlManager(e);});
        
        eval("canvasR"+i).addEventListener("mousedown",function(e){mdManager(e);});
        eval("canvasR"+i).addEventListener("mouseup",function(e){muManager(e);});
        eval("canvasR"+i).addEventListener("mouseenter",function(e){meManager(e);});
        eval("canvasR"+i).addEventListener("mouseleave",function(e){mlManager(e);});
    }
}

function mdManager(e){
    mousePos = [e.currentTarget.id.substring(6),compas(e.clientX,e.clientY,e.currentTarget)];
    if(paused)
        chronoContinue();
    document.getElementById(e.currentTarget.id).classList.add('vitrail-select');
}

function muManager(e){
    rotationManager(e);
    mousePos=[];
}

function meManager(e) {
    document.getElementById(e.currentTarget.id).classList.add('vitrail-hover');
}

function mlManager(e) {
    document.getElementById(e.currentTarget.id).classList.remove('vitrail-hover');
}        

function index()
{
    window.location.replace("./");
}

genVitraux();

toutDessiner(tab1,canvas1,ctx1);
toutDessiner(tab2,canvas2,ctx2);
toutDessiner(tab3,canvas3,ctx3);
toutDessiner(tab4,canvas4,ctx4);

empiler();
toutDessiner(tabTotal,canvasT,ctxT);

document.getElementById("stats").innerHTML = points+" points";

events();

if(!tutoMode)
{
    generate();
    chronoStart();
}

