<script>
    import Dice from '$lib/Dice.svelte';
    import { goto } from '$app/navigation';  
    import { enableBodyScroll, disableBodyScroll } from 'body-scroll-lock';
    import { sortable } from 'svelte-agnostic-draggable' ;
    import mapTouchToMouseFor from 'svelte-touch-to-mouse';

    export let data;


    // Si aucune party en cours retour home
    let my;
    if(!data.party)
        goto("/");
    else {
        my=data.player;
    }

    // % de taille des colonne de resultat =
    // type de dés = 2
    // nombre de jour 
    // +1 taille pour la colonne du joueur
    let colwidth=(data.players.length+3)/100;

    let dice1;
    let dice2;
    let dice3;
    let dice4;
    let dice5;
    let results=[];

    Edge.Client.addEventListener("message", async function(evt) {
        if(evt.detail.hasOwnProperty(data.party._id)) {
            console.log("RECEPTION MESSAGE");

            data=evt.detail[data.party._id];

            // Le propriétaire kill la partie
            if(data.party.status=="partykill") {
                my.partyid=null;
                Edge.Client.rpc("upsertPlayer",my);
                Edge.Client.rpc("deleteParty", data.party._id).catch(err => console.error(err));
                Edge.Client.send({ "cmd": "REFRESH"});
                goto("/");
            }

            // Le joueur est-il tjr dans le game
            let ingame=false;
            data.players.forEach(async(player) => {
                if(player._id===my._id) ingame=true;
            });
            if(!ingame) {
                window.location.href = '/';
            }

            // Action retour
            if(my._id===data.party.playercurrent._id) {
                console.log("ACTION = "+data.party.playerstatus);

                switch (data.party.playerstatus) {
                    case "dice":
                        data.party.playerparty = await Edge.Client.rpc("getPlayerParty", {playerid: data.party.playercurrent._id, partyid: data.party._id}).catch(err => console.error(err));
                        console.log(data.party.playerparty.tileid);
                        data.party.playertile = await Edge.Client.rpc("getTile",data.party.playerparty.tileid).catch(err => console.error(err));
                        console.log(data.party.playerparty);
                        console.log(data.party.playertile);
                    break;
                    
                    case "diceroll":
                        if(data.party.dices[0].value>0&&data.party.dices[1].value>0) {
                            data.party.playerdice+=data.party.dices[0].value;
                            data.party.playerdice+=data.party.dices[1].value;
                            // si resulat > 0 et non double = on passe à l'étape suivant sinon on peut rejeter
                            if(data.party.playerdice&&data.party.dices[0].value!=data.party.dices[1].value)
                                data.party.playerstatus="move";
                            else
                                data.party.playerstatus="dice";

                            sendMessage("DICEROLL to "+data.party.playerstatus);
                        }
                    break;

                    case "move":
                        console.log("MOVE + "+data.party.playerdice);
                        let position=parseInt(data.party.playertile.position)+parseInt(data.party.playerdice);

                        // Là il faut faire la régle de passage à par la casse week enk
                        // Voir si le mouve et super gros gérer le multipassage par weekend
                        if(position>27) position=position-27

                        // Mise à jour de la position du joueur
                        data.party.playertile.position=position;
                        console.log(data.party.playertile.position)
                        data.party.playertile = await Edge.Client.rpc("getTilebyorder",data.party.playertile.position).catch(err => console.error(err));
                        console.log(data.party.playertile);
                        data.party.playerparty.tileid=data.party.playertile._id;
                        Edge.Client.rpc("upsertPlayerParty",data.party.playerparty);

                        // temporaire on passe au suivant 
                        playernext();

                    break;
                }
            }
        }
    });

    function sendMessage(log) {
        console.log(log);
        Edge.Client.rpc("upsertParty", data.party).catch(err => console.error(err));
        Edge.Client.send({ [data.party._id]: data });
    }

    async function partyplay() {
        data.party.status="partyplay";
        data.party.playercurrent=data.players[0];
        sendMessage("START PARTY");
        Edge.Client.send({ "cmd": "REFRESH"});
    }
    
    async function partykill() {
        if (window.confirm("Voulez-vous vraiment supprimer la partie ?")) {
            data.party.status="partykill";
            sendMessage("KILL PARTY");
        }
    } 

    async function playerkill(id) {        
        if (window.confirm("Voulez-vous êtes sure de vous ?")) {
            // On supprime son resultat

            // Si le player courrant et celui killé on passe au suivant
            if(data.party.playercurrent._id==id) {
                // Rechercher le player suivant
                let nextplayer=0;
                data.players.forEach(async (player,i) => {     
                    if(player._id===data.party.playercurrent._id) {
                        if(data.players.hasOwnProperty(i+1))
                            nextplayer=i+1;
                        else
                            nextplayer=0;
                    }
                });      

                // Passer sur le player suivant
                data.party.playercurrent=data.players[nextplayer];

                // Reint les dices et round et diceresultchoiced
                var dices=[
                    {"id":1,"value":""},
                    {"id":2,"value":""},
                ];          
                data.party.round=0;
                data.party.dices=dices;
                data.party.diceresultchoiced=false;
            }

            // On supprime le player de la liste des players et on lui enlève la partie courrante
            data.players.forEach(async (player,i) => {     
                if(player._id===id) {
                    player.partyid=null;
                    Edge.Client.rpc("upsertPlayer",player);
                    data.players.splice(i,1);
                }
            });  

            // Si la partie est wait on libère une place
            if(data.party.status=="playerwait") {
                data.party.playernb-=1;
                Edge.Client.rpc("upsertParty",data.party);
                Edge.Client.send({ "cmd": "REFRESH"});
            }
            
            sendMessage("KILL PLAYER");
        }
    }

    function playernext() {
        // Rechercher le player suivant
        let nextplayer=0;
        data.players.forEach(async (player,i) => {     
            if(player._id===data.party.playercurrent._id) {
                if(data.players.hasOwnProperty(i+1))
                    nextplayer=i+1;
                else
                    nextplayer=0;
            }
        });      

        // Passer sur le player suivant
        data.party.playercurrent=data.players[nextplayer];

        // Reint des dices
        var dices=[
            {"id":1,"value":""},
            {"id":2,"value":""}
        ];        
        data.party.dices=dices;

        // Reinit du score du dice
        data.party.playerdice=0;

        // Reinit du statut du player
        data.party.playerstatus="dice"
                
        sendMessage("NEXT PLAYER");
        window.scrollTo(0, 0);
    }    

    async function partysave() {
        let myresult=0;
        results.forEach(async (result) => {  
            if(result.player._id===my._id) myresult=result.value;
        });
        my.nbparty=(my.nbparty?my.nbparty:0)+1;
        my.scorecumul=(my.scorecumul?my.scorecumul:0)+myresult;
        my.scoremax=(my.scoremax?my.scorecumul:0);
        my.scoremax=(my.scoremax<myresult?myresult:my.scoremax);
        my.partyid=null;
        await Edge.Client.rpc("upsertPlayer", my).catch(err => console.error(err));
        goto("/");
    }
        
    function diceresult(event) {
        data.party.dices.forEach(async (dice,id) => {
            if(dice.id===event.detail.id) {
                data.party.dices[id].value=event.detail.value;
            }
        });

        data.party.playerstatus="diceroll";
        sendMessage("RESULT ROLL");
    }

    async function roll() {
        await data.party.dices.forEach(async (dice) => {
            switch (dice.id) {
                case 1: await dice1.roll(); break;
                case 2: await dice2.roll(); break;
            }
        });        

        
        
        //sendMessage("NEXT ROLL");
        window.scrollTo(0, 0);
    }




   
</script>

{#if data.party }
    <div class="sticky bg-white dark:bg-gray-900 pt-3" style="top:65px">
        <!-- LISTE DES JOUEURS -->
        <div class="flex wrap mb-3 items-center justify-center">
            {#each data.players as player}
                {#if player._id===data.party.playercurrent._id && data.party.status!="partyend"}
                    <div class="flex flex-col p-1 w-20 h-20 md:w-28 md:h-28 items-center justify-center bg-lime-500 mx-1 text-black">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="hidden md:block w-10 h-10 text-cyan-950">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>

                        <span class="text-xs text-center">Joueur<br><span class="{(player._id==my._id?"text-3xl":"")}">{(player._id==my._id?"MOI":player.name)}</span></span>

                        {#if my._id===data.party.playerid && my._id!==player._id}
                            <button on:click={playerkill(player._id)}>sortir</button>
                        {/if}
                    </div>
                {:else}
                    <div class="flex flex-col p-1 w-20 h-20 md:w-28 md:h-28 items-center justify-center bg-gray-200 mx-1 text-black">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="hidden md:block w-10 h-10">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                        
                        <span class="text-xs text-center">Joueur<br><span class="{(player._id==my._id?"text-3xl":"")}">{(player._id==my._id?"MOI":player.name)}</span></span>

                        {#if my._id===data.party.playerid && my._id!==player._id}
                            <button on:click={playerkill(player._id)}>sortir</button>
                        {/if}
                    </div>            
                {/if}
            {/each}
        </div>

        <!-- PARTIE EN ATTENTE -->
        {#if data.party.status==="playerwait"}
            <div class="text-center">
                en attente de joueurs<br>
                <span class="text-3xl">{data.party.playernb} sur {data.party.playernbmax}</span>
                {#if my._id===data.party.playerid }
                    <button class="w-full bg-lime-500 hover:bg-lime-400 mt-3 text-black text-3xl p-3" on:click={partyplay}>
                        Démarrer la Partie
                    </button>        
                    <button class="w-full bg-red-500 hover:bg-red-400 mt-3 text-black text-3xl p-3" on:click={partykill}>
                        Supprimer la Partie
                    </button>                  
                {/if}
            </div>

        <!-- FIN DE PARTIE -->
        {:else if data.party.status==="partyend"}
            <div class="text-center">
                FIN de PARTIE
                <button class="w-full bg-lime-500 hover:bg-lime-400 mt-3 text-black md:text-3xl p-3" on:click={partysave}>
                    Enregistrer mon score et sortir
                </button>                 
            </div>
        
        <!-- ACTION DU JEU -->
        {:else if data.party.playercurrent._id===my._id}
            <div class="md:text-3xl text-center">
                MON TOUR
            </div>
            <div class="mt-3">
                {#if data.party.playerstatus=="dice"}
                <button class="w-full bg-lime-500 hover:bg-lime-400 text-2xl md:text-3xl mb-3 text-black" on:click={roll}>
                    <div>Jetter les dés</div>
                </button>
                {:else}
                <button class="w-full bg-lime-500 hover:bg-lime-400 md:text-3xl mb-3 text-black p-3" on:click={playernext}>
                    Prochain Joueur
                </button>
                {/if}
            </div>
        {:else}
            <div class="md:text-3xl text-center">TOUR du Joueur = {data.party.playercurrent.name}</div>
        {/if}
    </div>

    <!-- PARTY -->
    {#if data.party.status!=="playerwait" && data.party.status!=="partyend"}
        {#if data.party.playercurrent._id===my._id}
            <div class="flex flex-wrap">
                <div use:sortable={{cursor:'grabbing', zIndex:100}} class="w-full flex flex-wrap p-1 bg-lime-500 items-center justify-center rounded-lg border-8 border-black">
                    {#each data.party.dices as mydice}
                        {#if mydice.id === 1}
                            <Dice bind:this={dice1} {...mydice} on:diceresult={diceresult} />
                        {:else if mydice.id === 2}
                            <Dice bind:this={dice2} {...mydice} on:diceresult={diceresult} />
                        {/if}
                    {/each}
                </div>
            </div>
        {:else}
            <div class="flex flex-wrap">
                <div class="w-full flex flex-wrap p-1 md:p-5 bg-lime-500 items-center justify-center rounded-lg border-8 border-black">
                    {#each data.party.dices as mydice}
                        {#if !mydice.selected}
                            <span class="cursor-pointer text-3xl flex justify-center items-center bg-red-600 text-white rounded-lg m-1 w-14 h-14 md:m-3 md:w-20 md:h-20">
                                {mydice.value}
                            </span>
                        {/if}
                    {/each}
                </div>
            </div>
        {/if}
    {/if}

    <div>
        {#if data.party.playertile }
            Nom = {data.party.playertile.name}<br>
            Position = {data.party.playertile.position}<br>
            
            <img src="{data.party.playertile.img}" alt="tile" style="width:800px; max-width: 100%; margin:auto;">
        {/if}
    </div>

    <!-- KILL -->
    {#if data.party.status==="partyplay" && my._id===data.party.playerid }
    <button class="w-full bg-red-500 hover:bg-red-400 mt-3 text-black md:text-3xl p-1 md:p-3" on:click={partykill}>
        Supprimer la Partie
    </button>                  
    {/if}

    <!-- SORTIR -->
    {#if my._id!==data.party.playerid }
        <button class="w-full bg-red-500 hover:bg-red-400 mt-3 text-black md:text-3xl p-1 md:p-3" on:click={playerkill(my._id)}>
            Quitter la Partie
        </button>                  
    {/if}

{/if}