const base_url = "https://oss110metz.rezo-rm.fr/"

var page = ['#main-page', '#admin-page', '#login-page', '#demande-page'];
window.onpopstate = history.onpushstate = function(e) {
    if (e.state) {
        show_page(e.state, true);
    } else {
        history.back();
    }
};
history.pushState("#main-page", "", "")

var save_udpate= null;

function show_page(id, historyPush) {
    //si le z-index de la nouvelle page est inférieur on fait un transi 'forward' sinon 'backward'
    for(i in page) {
        $(page[i]).hide().removeClass("away");
    }

    $hs = $(history.state).show();
    if(!historyPush)
        $hs.addClass('away');
    $id = $(id).show();

    /*if(id == "#demande-page") {
        save_udpate = setInterval(() => {
            let save_scroll = $(window).scrollTop();
            updateDemandes();
            $(window).scrollTop(save_scroll);
        }, 5000);
    } else if (!save_udpate) {
        clearInterval(save_udpate);
    }*/

    if(!historyPush) {
        history.pushState(id, "", "")
    }
}

//show_page("#demande-page");

$("#login-button").click(function (e) {
    var data = JSON.stringify({
        user: $("#login").val().trim(),
        password: $("#password").val().trim()
    });
    $("#password").val('');
    $.ajax({
        type: "POST",
        url: base_url + "login",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (data) {
            if(data.success) {
                localStorage.setItem("token", data.token);
                localStorage.setItem("user", data.user.uid);
                localStorage.setItem("isAdmin", data.user.isAdmin);
                if (data.user.isAdmin) {
                    show_page('#admin-page');
                    get_admin("prank");
                } else {
                    show_page('#demande-page');
                    updateDemandes();
                }
            } else {
                $('#error-message').empty();
                t = new TypeIt('#error-message', {
                    speed: 110,
                    lifeLike: true
                })
                .type(data.why)
                .go();
            }

        },
        error: function(e, status, i) {
            $('#error-message').empty();
            t = new TypeIt('#error-message', {
                speed: 110,
                lifeLike: true
            })
            .type(status)
            .go();
        }
    });

});

$("#register-button").click(function (e) {
    var data = JSON.stringify({
        user: $("#register-user").val().trim(),
        password: $("#register-password").val().trim()
    });
    if( $("#register-password-confirm").val() != $("#register-password").val()) {
        t = new TypeIt('#error-message-register', {
            speed: 100,
            lifeLike: true
        })
        .type("Oups, les 2 mots de passe ne correspondent pas !")
        .go();
        return;
    }
    $("#register-password").val('');
    $("#register-password-confirm").val("");
    $.ajax({
        type: "POST",
        url: base_url + "register",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (data) {
            if(data.success) {
                localStorage.setItem("token", data.token);
                localStorage.setItem("user", data.user.uid);
                localStorage.setItem("isAdmin", data.user.isAdmin);
                if (data.user.isAdmin) {
                    show_page('#admin-page');
                    get_admin("prank");
                } else {
                    show_page('#demande-page');
                    updateDemandes();
                }
            } else {
                $('#error-message-register').empty();
                t = new TypeIt('#error-message-register', {
                    speed: 110,
                    lifeLike: true
                })
                .type(data.why)
                .go();
            }

        },
        error: function(e, status, i) {
            $('#error-message-register').empty();
            t = new TypeIt('#error-message-register', {
                speed: 110,
                lifeLike: true
            })
            .type(status)
            .go();
        }
    });

});

$("#prank-button").click(function () {
    if (localStorage.getItem('token')) {
        show_page('#demande-page');
        updateDemandes();
    }
    else {
        show_page('#login-page');
    }
});

$("#logo").click(function () {
    if (localStorage.getItem('token')) {
        if (localStorage.getItem('isAdmin')) {
            show_page('#admin-page');
            // Load prank by default
            get_admin("prank");
        }
        else {
            show_page('#demande-page');
            updateDemandes();
        }
    }
    else {
        show_page('#login-page');
    }
});

$("#admin-prank").click(() => {
    get_admin("prank");
})
$("#admin-treasure").click(() => {
    get_admin("treasure");
})
$("#admin-activity").click(() => {
    get_admin("activity");
})

function get_admin(type) {
    $("#admin-content").empty();
    $.ajax({
        type: "POST",
        url: base_url + "get",
        data: JSON.stringify({
            uid: localStorage.getItem('user'),
            token: localStorage.getItem('token'),
            type: type,
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (data) {
            if(data.success) {
                switch (type) {
                    case "prank":
                        let doneCnt = 0;
                        let prankData = [];
                        for (prankUid in data.prankData) {
                            data.prankData[prankUid].prankUid = prankUid;
                            prankData.push(data.prankData[prankUid]);
                        }
                        prankData.sort((a, b) => new Date(a.date) - new Date(b.date));
                        for (entry in prankData) {
                            switch (prankData[entry].type) {
                                case "crêpe":
                                    if (prankData[entry].state == "Pending"
                                    || prankData[entry].state == "Accepted") {
                                        $("#admin-content").append(`
                                            <span id="${prankData[entry].prankUid}" class="prank">
                                                <div class="prank-title">Demande de crêpe par ${prankData[entry].creator}</div>
                                                <div class="prank-amount">Quantité: ${prankData[entry].amount}</div>
                                                <div class="prank-supplement">Garniture: ${prankData[entry].supplement}</div>
                                                <div class="prank-where">Livraison: ${prankData[entry].where}</div>
                                                <div class="prank-note">Livraison: ${prankData[entry].note}</div>
                                                <span class="prank-footer">
                                                    <div class="prank-uid">UID: ${prankData[entry].prankUid}</div>
                                                    <div class="prank-date">DATE: ${prankData[entry].date}</div>
                                                </span>
                                                <span class="prank-btn">
                                                    <div class="prank-btn-accept" style="display: ${(prankData[entry].state == "Accepted" && prankData[entry].manageBy == localStorage.getItem("user")) ? "none" : "flex"};">${(prankData[entry].state == "Pending") ? "Accepter" : "Récupérer (accepté par: "+prankData[entry].manageBy+")"}</div>
                                                    <div class="prank-btn-done" style="display: ${(prankData[entry].state == "Accepted" && prankData[entry].manageBy == localStorage.getItem("user")) ? "flex" : "none"};">Done</div>
                                                    <div class="prank-btn-refused">Refuser</div>
                                                </span>
                                            </span>
                                        `)
                                    } else if(prankData[entry].state == "Done") {
                                        doneCnt++;
                                    }
                                    break;
                                case "kidnap":
                                    // Not Handle
                                    break;
                            }
                        }
                        $.ajax({
                            type: "POST",
                            url: base_url + "get",
                            data: JSON.stringify({
                                uid: localStorage.getItem('user'),
                                token: localStorage.getItem('token'),
                                type: "state"
                            }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            async: false,

                            success: function(data) {
                                if(data.success) {
                                    if(data.state == "open") {
                                        var text = 'Vérouiller';
                                    } else {
                                        var text = 'Dévérouiller';
                                    }
                                    $('#admin-content').append(`
                                        <span class="prank">
                                            <div>Changer l'état de commande de crêpe :</div>
                                            <span class="prank-btn">
                                                <div id="switch-state">${text}</div>
                                            </span>
                                        </span>
                                    `);
                                }
                            }
                        });

                        $("#admin-content").append(`
                            <span class="prank">
                                <div id=prankDone>Nombre totale de missions achevées: ${doneCnt}</div>
                            </span>
                        `);
                        break;
                    case "treasure":
                        let treasureData = [];
                        for (treasureUid in data.treasureData) {
                            data.treasureData[treasureUid].treasureUid = treasureUid;
                            treasureData.push(data.treasureData[treasureUid]);
                        }
                        treasureData.sort((a, b) => new Date(a.date) - new Date(b.date));
                        for (entry in treasureData) {
                            if (treasureData[entry].state == "Pending") {
                                $("#admin-content").append(`
                                    <span id="${treasureData[entry].treasureUid}" class="treasure">
                                        <div class="treasure-title">Demande de vérification par ${treasureData[entry].creator}</div>
                                        <div class="treasure-activity">Activité: ${treasureData[entry].activity.title}</div>
                                        <div class="treasure-desc">Description: ${treasureData[entry].desc}</div>
                                        <div class="treasure-image">Image: <a href="${base_url}images/${treasureData[entry].image}.html" target="_blank"> Lien</a></div>
                                        <span class="treasure-footer">
                                            <div class="treasure-uid">UID: ${treasureData[entry].treasureUid}</div>
                                            <div class="treasure-date">DATE: ${treasureData[entry].date}</div>
                                        </span>
                                        <span class="treasure-btn">
                                            <div class="treasure-btn-accept">Accepter</div>
                                            <div class="treasure-btn-refused">Refuser</div>
                                        </span>
                                    </span>
                                `)
                            }
                        }
                        break;
                    case "activity":
                        let activityData = [];
                        for (activityUid in data.activityData) {
                            data.activityData[activityUid].activityUid = activityUid;
                            activityData.push(data.activityData[activityUid]);
                        }
                        activityData.sort((a, b) => new Date(a.start) - new Date(b.start));
                        for (entry in activityData) {
                            if (activityData[entry].type == "event") {
                                $("#admin-content").append(`
                                    <span id="${activityData[entry].activityUid}" class="activity">
                                        <div class="activity-title">Event: <textarea class="admin-textarea">${activityData[entry].title}</textarea></div>
                                        <div class="activity-desc">Description: <textarea class="admin-textarea">${activityData[entry].desc}</textarea></div>
                                        <div class="activity-where">Lieu: <textarea class="admin-textarea">${activityData[entry].where}</textarea></div>
                                        <div class="activity-start">Début: <input type="datetime-local" class="admin-input-date" value="${toIsoString(new Date(activityData[entry].start))}"></input></div>
                                        <div class="activity-end">Fin: <input type="datetime-local" class="admin-input-date" value="${toIsoString(new Date(activityData[entry].end))}"></input></div>
                                        <span class="activity-footer">
                                            <div class="activity-uid">UID: ${activityData[entry].activityUid}</div>
                                        </span>
                                        <span class="activity-btn">
                                            <div class="activity-btn-update">Update</div>
                                            <div class="activity-btn-delete">Supprimer</div>
                                        </span>
                                    </span>
                                `)
                            } else if (activityData[entry].type == "treasure") {
                                $("#admin-content").prepend(`
                                    <span id="${activityData[entry].activityUid}" class="activity">
                                        <div class="activity-title">Trésor: <textarea class="admin-textarea">${activityData[entry].title}</textarea></div>
                                        <div class="activity-desc">Description: <textarea class="admin-textarea">${activityData[entry].desc}</textarea></div>
                                        <div class="activity-where">Lieu: <textarea class="admin-textarea">${activityData[entry].where}</textarea></div>
                                        <div class="activity-start">Début: <input type="datetime-local" class="admin-input-date" value="${toIsoString(new Date(activityData[entry].start))}"></input></div>
                                        <div class="activity-state">Status: ${activityData[entry].treasureState}</div>
                                        <span class="activity-footer">
                                            <div class="activity-uid">UID: ${activityData[entry].activityUid}</div>
                                        </span>
                                        <span class="activity-btn">
                                            <div class="activity-btn-update">Update</div>
                                            <div class="activity-btn-delete">Supprimer</div>
                                        </span>
                                    </span>
                                `)
                            }
                        }
                        $("#admin-content").prepend(`
                            <span id="addActivity" class="activity">
                                <label for="activityType">Choisir une option:</label>
                                <select name="type" id="activityType">
                                    <option value="event">Event</option>
                                    <option value="treasure">Trésor</option>
                                </select>
                                <div class="activity-title">Titre: <textarea class="admin-textarea"></textarea></div>
                                <div class="activity-desc">Description: <textarea class="admin-textarea"></textarea></div>
                                <div class="activity-where">Lieu: <textarea class="admin-textarea"></textarea></div>
                                <div class="activity-start">Début: <input type="datetime-local" class="admin-input-date"></input></div>
                                <div id="activity-end-add" class="activity-end">Fin: <input type="datetime-local" class="admin-input-date"></input></div>
                                <span class="activity-btn">
                                    <div id="activity-btn-add">Ajouter une activité</div>
                                </span>
                            </span>
                        `)
                        break;
                }
                refreshListener();
            } else {
                if (data.why == "Not authentificated") {
                    show_page('#login-page');
                } else {
                    alert(data.why);
                }
            }
        }
    });
}

function refreshListener() {

    $(".prank-btn-accept").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "acceptPrank",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                prankUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    let btnElems = $("#"+uid).children()[6];
                    btnElems.children[0].style.display = "none";
                    btnElems.children[1].style.display = "flex";
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })

    $(".prank-btn-refused").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "refusePrank",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                prankUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $("#"+uid).remove();
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })

    $(".prank-btn-done").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "donePrank",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                prankUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $("#"+uid).remove();
                    $("#prankDone")[0].innerHTML = "Nombre totale de mission achevées: " + (parseInt($("#prankDone")[0].innerHTML.replace("Nombre totale de mission achevées: ", "")) + 1);
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })

    $(".treasure-btn-accept").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "acceptTreasure",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                treasureUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $("#"+uid).remove();
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })

    $(".treasure-btn-refused").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "refuseTreasure",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                treasureUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $("#"+uid).remove();
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })
    $(".activity-btn-update").click((e) => {
        let uid = e.target.parentNode.parentNode.id;
        let children = e.target.parentNode.parentNode.children;
        $.ajax({
            type: "POST",
            url: base_url + "addActivity",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                activityUid: uid,
                type: (children[0].innerHTML.substring(0, 5) == "Event") ? "event" : "treasure",
                title: children[0].children[0].value,
                desc: children[1].children[0].value,
                where: children[2].children[0].value,
                start: new Date(children[3].children[0].value).toString(),
                end: (children[3].children.length == 0) ? null : new Date(children[4].children[0].value).toString(),
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    alert("Update réussie")
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })
    $(".activity-btn-delete").click((e) => {
        let uid = e.target.parentNode.parentNode.id
        $.ajax({
            type: "POST",
            url: base_url + "delActivity",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                activityUid: uid,
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $("#"+uid).remove();
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })
    $("#activityType").on("change", function() {
        if (this.value == "treasure") {
            $("#activity-end-add").css("display", "none");
        } else if (this.value == "event") {
            $("#activity-end-add").css("display", "flex");
        }
    })
    $("#activity-btn-add").click((e) => {
        let children = e.target.parentNode.parentNode.children;
        $.ajax({
            type: "POST",
            url: base_url + "addActivity",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: $("#activityType").val(),
                title: children[2].children[0].value,
                desc: children[3].children[0].value,
                where: children[4].children[0].value,
                start: new Date(children[5].children[0].value).toString(),
                end: ($("#activityType").val() == "treasure") ? null : new Date(children[6].children[0].value).toString(),
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    get_admin("activity");
                } else {
                    if (data.why == "Not authentificated") {
                        show_page('#login-page');
                    } else {
                        alert(data.why);
                    }
                }
            }
        });
    })
    $(".prank-btn-delete").click((e) => {
        let uid = e.target.parentNode.parentNode.id;
        $.ajax({
            type: 'POST',
            url: base_url + 'delPrank',
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                prankUid: uid
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function(data) {
                if (data.success) {
                    updateDemandes();
                }
                else {
                    alert(data.why);
                }
            }

        });
    });
    $(".treasure-btn-submit").click((e) => {
        let uid = e.target.parentNode.parentNode.id;

        $('#treasure-popup-activity-uid').val(uid);
        $('#treasure-popup-uid').val($('#' + uid + ' .treasure-uid').text());
        $('#treasure-popup-title').text($('#' + uid + ' .treasure-title').text());
        $('#treasure-popup-desc').text($('#' + uid + ' .treasure-user-desc').text());

        $('.overlay').css({"opacity": 1, "visibility": "visible"});
    });
    $('#switch-state').click((e) => {
        $.ajax({
            type: "POST",
            url: base_url + "switchState",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                if(data.state == 'open') {
                    $("#switch-state").text('Vérouiller');
                } else {
                    $("#switch-state").text('Dévérouiller');
                }
            }
        });

    });
}

$('.close').click((e) => {
    $('.overlay').css({"opacity": 0, "visibility": "hidden"});
});

$('#treasure-popup-button').click((e) => {
    var fr = new FileReader();
    let f = $('#treasure-popup-image').prop('files')[0];
    if(f.size > 10**7) {
        alert('Le fichier est beaucoup trop gros !');
        return;
    }

    var indata = {
        uid: localStorage.getItem('user'),
        token: localStorage.getItem('token'),
        activityUid: $('#treasure-popup-activity-uid').val(),
        desc: $('#treasure-popup-desc').text(),
    }
    var tuid = $('#treasure-popup-uid').val();
    if(tuid != '') {
        indata.treasureUid = tuid;
    }

    fr.addEventListener('load', () => {
        indata.image = fr.result;
        $.ajax({
            type: "POST",
            url: base_url + "sendTreasure",
            data: JSON.stringify(indata),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function(data) {
                if(data.success) {
                    updateDemandes();
                    $('.overlay').css({"opacity": 0, "visibility": "hidden"});
                } else {
                    console.error(data.why);
                }
            }
        });
    });



    fr.readAsDataURL(f);
});

function refreshCrepe() {
    $('#demande-button').click(function () {
        amount = $('#demande-amount').val();
        if (amount > 9) {
            t = new TypeIt('#error-message-demande', {
                speed: 100,
                lifeLike: true
            })
            .type("Trop de crêpes, maximum c'est 9")
            .go();
            return;
        }
        $.ajax({
            type: "POST",
            url: base_url + "addPrank",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: "crêpe",
                amount: amount,
                where: $('#demande-where').val(),
                supplement: $('#demande-supp').val(),
                note: $('#demande-notes').val(),
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function(data) {
                if(data.success) {
                    $('#demande-form input').val("");
                    alert("C'est envoyé, gros gourmand ^^")
                    updateDemandes();
                } else {
                    $('#error-message-demande').empty();
                    t = new TypeIt('#error-message-demande', {
                        speed: 100,
                        lifeLike: true
                    })
                    .type(data.why)
                    .go();
                    if(data.why.startsWith('Token expired') || data.why.startsWith('Not authen'))
                        show_page("#login-page");
                }
            }
        });
    });
}

var saved_form = $('#demande-form').html();

function is_locked() {

}

function updateDemandes() {

    if(localStorage.getItem('user') && localStorage.getItem('token')) {
        $.ajax({
            type: "POST",
            url: base_url + "get",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: "state"
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function(data) {
                if(data.success) {
                    if(data.state == "open") {
                        $('#demande-form').html(saved_form);
                        refreshCrepe();
                    } else {
                        $('#demande-form').html('<h2>Les commandes sont fermés pour le moment mais on revient vite !</h2>');
                    }
                }
            }
        });

        $.ajax({
            type: "POST",
            url: base_url + "get",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: "prank"

            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $('#demande-list').html('');
                    let pd = [];
                    for (pd_uid in data.prankData) {
                        if (data.prankData[pd_uid].creator == localStorage.getItem('user')) {
                            data.prankData[pd_uid].prankUid = pd_uid;
                            pd.push(data.prankData[pd_uid]);
                        }
                    }
                    pd.sort((a, b) => new Date(b.date) - new Date(a.date));
                    for(const pd_uid in pd) {
                        $('#demande-list').append(`
                        <span id="${pd[pd_uid].prankUid}" class="prank">
                            <h2 class="prank-title">Demande de crêpe</h2>
                            <div class="prank-amount">Quantité: ${pd[pd_uid].amount}</div>
                            <div class="prank-supplement">Garniture: ${pd[pd_uid].supplement}</div>
                            <div class="prank-where">Livraison: ${pd[pd_uid].where}</div>
                            <div class="prank-note">Notes: ${pd[pd_uid].note}</div>
                            <div class="prank-status">Statue: ${pd[pd_uid].state}</div>
                            <span class="prank-footer">
                                <div class="prank-uid">UID: ${pd[pd_uid].prankUid}</div>
                                <div class="prank-date">DATE: ${pd[pd_uid].date}</div>
                            </span>
                            ${  (pd[pd_uid].state != "Accepted" && pd[pd_uid].state != "Refused" ) ?
                                    `<span class="prank-btn">
                                        <div class="prank-btn-delete">Annuler</div>
                                    </span>`
                                : ''
                            }
                        </span>
                        `)
                    }
                    refreshListener();
                }
                else {
                    if (data.why == "Not authentificated" || data.why == "Token expired") {
                        show_page('#login-page');
                    } else {
                        console.error(data.why);
                    }
                }
            }

        });
        $.ajax({
            type: "POST",
            url: base_url + "get",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: "activity"

            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    $('#treasure-list').html('');

                    let ad = data.activityData;

                    for(const ad_uid in ad) {
                        if(ad[ad_uid].type == "treasure") {
                        $('#treasure-list').append(`
                            <span id="${ad_uid}" class="treasure ${ad[ad_uid].treasureState == "Accepted" ? "treasure-accepted" : ""}">
                                <h2 class="treasure-title">${ad[ad_uid].title}</h2>
                                ${ ad[ad_uid].where ? `<div class="treasure-reward">Récompense : ${ad[ad_uid].where}</div>` : "" }
                                <div class="treasure-desc">Validité: ${ad[ad_uid].desc}</div>
                                <div class="treasure-status">Statue: ${ad[ad_uid].treasureState}</div>
                                ${  (ad[ad_uid].treasureState != "Accepted" && ad[ad_uid].treasureState != "Refused" ) ?
                                        `<span class="treasure-btn">
                                            <div class="treasure-btn-submit">Soumettre sa résolution</div>
                                        </span>`
                                    : ''
                                }
                            </span>
                            `)
                        }
                    }
                    refreshListener();
                }
                else {
                    console.error(data.why);
                }
            }
        });
        $.ajax({
            type: "POST",
            url: base_url + "get",
            data: JSON.stringify({
                uid: localStorage.getItem('user'),
                token: localStorage.getItem('token'),
                type: "treasure"

            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (data) {
                if(data.success) {
                    let td = data.treasureData;

                    for(const td_uid in td) {
                        if(td[td_uid].treasureState != "Accepted") {
                            $elem = $('#' + td[td_uid].activityUid);
                            if(td[td_uid].treasureState == "Refused")
                                $elem.addClass('treasure-refused');
                            else
                                $elem.addClass('treasure-submitted');
                            $elem.find(".treasure-btn-submit").text('Editer la soumission');

                            $(`<div class="treasure-image">Image: <a href="${base_url}images/${td[td_uid].image}.html" target="_blank"> Lien</a></div>`).insertAfter($elem.find('.treasure-desc'))
                            $(`<div class="treasure-user-desc">${td[td_uid].desc}</div>`).insertAfter($elem.find('.treasure-desc'))
                            $(`<p>Votre soumission :</p>`).insertAfter($elem.find('.treasure-desc'))
                            $(`<span class="treasure-footer">
                                <div class="treasure-uid">${td_uid}</div>
                            </span>`).insertAfter($elem.find('.treasure-btn'));
                        }
                    }
                    refreshListener();
                }
                else {
                    console.error(data.why);
                }
            }

        });
    }
}

function updateNextActivity() {
    $.ajax({
        type: "POST",
        url: base_url + "get",
        data: JSON.stringify({
            token: "",
            uid: "",
            type: "activity",
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: (data) => {
            if(data.success) {
                let curr_date = new Date();
                let ad = data.activityData;
                var candidate = [];
                var next_acti = {title: "Pas encore d'activité", desc: "Encore aucune activité n'a été renseigné, faite le vite !"};
                for(const uid in ad) {
                    if(ad[uid].type == "event" && curr_date < new Date( ad[uid].start )) {
                        candidate.push(ad[uid]);
                    }
                }

                next_acti = candidate.reduce(function(prev, curr) {
                    return new Date(prev.start) < new Date(curr.start) ? prev : curr;
                });

                $(["#activite-title","#activite-desc","#activite-place"]).text('');

                var opt = {speed: 100};
                new TypeIt("#activite-title", opt)
                    .type(next_acti.title)
                    .go();
                new TypeIt("#activite-desc", opt)
                    .type(next_acti.desc)
                    .go();
                new TypeIt("#activite-place", opt)
                    .type("Lieu : " + next_acti.where)
                    .go();
                let diff = Math.ceil( (new Date(next_acti.start) - new Date()) / 1000 )
                let days = Math.trunc(diff / (3600*24) )
                let h = Math.trunc(diff / 3600) - days*24
                let m = Math.trunc(diff / 60) - (h + days*24)*60
                let s = diff - h*3600 - m*60 - days*24*3600
                $('#timer').text((days == 0  ? "" : days + " jours ") + (new Date('December 17, 1995 ' + [h, m, s].join(':'))).toLocaleTimeString('default', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                }));
            }
        }
    })
}

$(window).on("load", function() {
    /* Register the Service Worker */
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('./js/sw.js');
    }

    for(i in page) {
        $(page[i]).css('z-index', page.length - i);
    }

    updateNextActivity();
    refreshCrepe();

    /* load timer */
    window.setInterval(function() {
        var b = $("#timer").text().split(' jours ');
        if(b.length == 2) {
            var time = b[1];
            var days = b[0];
        } else {
            var time = b[0];
            var days = 0;
        }
        var t = time.split(":").map(t => parseInt(t));

        t[2] -= 1;
        if (t[2] < 0) {
            t[2] = 59;
            t[1] -= 1;
        }
        if (t[1] < 0) {
            t[1] = 59;
            t[0] -= 1;
        }
        if (t[0] < 0) {
            t[0] = 23;
            t[1] = 59;
            t[2] = 59;
            days -= 1;
        }
        if (days < 0) {
            t[0] = 0;
            t[1] = 0;
            t[2] = 0;
            days = 0;
            updateNextActivity();
        }
        $('#timer').text( (days == 0  ? "" : days + " jours ") + (new Date('December 17, 1995 ' + t.join(':'))).toLocaleTimeString('default', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }));

    }, 1000);
});

function toIsoString(date) {
  var tzo = -date.getTimezoneOffset(),
      dif = tzo >= 0 ? '+' : '-',
      pad = function(num) {
          return (num < 10 ? '0' : '') + num;
      };

  return date.getFullYear() +
      '-' + pad(date.getMonth() + 1) +
      '-' + pad(date.getDate()) +
      'T' + pad(date.getHours()) +
      ':' + pad(date.getMinutes()) +
      ':' + pad(date.getSeconds());
}
