// Initialize Firebase
var config = {
    apiKey: "AIzaSyCuvwf78cmSDoZ2yS4XxHZhnjUn7yIHYfw",
    authDomain: "test-667ca.firebaseapp.com",
    databaseURL: "https://test-667ca.firebaseio.com",
    projectId: "test-667ca",
    storageBucket: "test-667ca.appspot.com",
    messagingSenderId: "221332577314"
};


firebase.initializeApp(config);



$(document).ready(function () {
    firebase.auth().onAuthStateChanged(async function (user) {
        if (user) {
            firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                console.log("/shoppinglistx idtoken:", idtoken);
                var url = "/dash/" + idtoken
                console.log("URL: ", url)
                $('#dashurl').attr("href", url);

            }).catch((error) => console.error("/shoppinglist Get id token client error: ", error));
        } else {
            console.log("Check Auth error", user)
        }
    });

    eigeneEinkaufslisten();
    geteilteEinkaufslisten();

    $(".detailcardausgabe").hide();

    $(".logout").click(function () {
        console.log("click logout")
        firebase.auth().signOut().then(function () {
            document.location.replace('/');
        }).catch(function (error) {
            console.error("Logout Error: ", error)
        });
    });

    $('.add').click(function () {
        console.log("click add");
        // let name = $("#einkaufslistenname").val();

        firebase.auth().onAuthStateChanged(async function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                    console.log("/shoppinglistx idtoken:", idtoken);
                    $.ajax({
                        type: "POST",
                        url: "/shoppinglist",
                        data: {
                            name: $("#einkaufslistenname").val(),
                            description: $("#einkaufslistenbeschreibung").val(),
                            color: $("input:checked").val(),
                            idtoken: idtoken
                        },
                        success(res) {
                            console.log("add funktioniert");
                            $(".listen-ausgabe").html("");
                            eigeneEinkaufslisten();
                            geteilteEinkaufslisten();
                            $(".EigeneListeAdd").modal("hide");
                        },
                        error(err) {
                            console.log("/shoppinglist error", err);
                        }
                    });
                }).catch((error) => console.error("/shoppinglist Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });

    });

    $(".sl_add").click(function () {
        $('#EigeneListeAdd').modal('show');
    });

});

var globaleAddZwischenID = "";
var globalegraddid = "";
// var globaleGetZwischenID = "";

function eigeneEinkaufslisten() {
    firebase.auth().onAuthStateChanged(async function (user) {
        if (user) {
            firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                console.log("/myshoppinglists idtoke: ", idtoken);
                $.ajax({
                    type: "GET",
                    url: "/myshoppinglists",
                    data: {
                        idtoken: idtoken
                    },
                    success(res) {
                        firebase.auth().onAuthStateChanged(async function (user) {
                            if (user) {
                                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                                    console.log("/userinfo_json idtoken: ", idtoken)
                                    $.ajax({
                                        type: "GET",
                                        url: "/userinfo_json",
                                        data: {
                                            idtoken: idtoken
                                        },
                                        success(data) {
                                            const userinfo = data.name;
                                            const picture = data.picture;
                                            console.log(data)
                                            for (let i = 0; i < res.length; i++) {
                                                const el = res[i];

                                                $(".listen-ausgabe").append(`<div class="col-md-12 karten">
                                <div class="card border-light mb-3 shadow-sm" style="max-width: 18rem;" id="${el.sl_id}">
                                    <div class="card-header" style="background-color: #${el.color};">
                                    <span>
                                    <img src="${picture}" alt="Avatar" style="width:10%; border-radius: 50%;">
                                        ${userinfo}</span>
                                        <button class="btn edit"><i class="fas fa-pencil-alt "></i></button>
                                        <button class="btn trash"><i class="far fa-trash-alt"></i></button>
                                    </div>
                                    
                                    <div class="card-body">
                                        <h5 class="card-title">${el.name}</h5>
                                        <p class="card-text">${el.description}</p>
                                    </div>
                                </div></div>`)
                                            }
                                            console.log("Eigene Einkaufslisten");
                                            loeschen();
                                            Detail();
                                            // groupHinzufügen()
                                        },
                                        error(err) {
                                            console.error("userinfo_json error: ", err)
                                        }
                                    })
                                }).catch((error) => console.error("Get id token client error: ", error));
                            } else {
                                console.log("Check Auth error", user)
                            }
                        });
                    },
                    error(err) {
                        console.error("/myshoppinglists ajax error: ", err);
                    }
                });
            }).catch((error) => console.error("Get id token client error: ", error));
        } else {
            console.log("Check Auth error", user)
        }
    });
};

function geteilteEinkaufslisten() {
    firebase.auth().onAuthStateChanged(async function (user) {
        if (user) {
            firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                console.log("/sharedshoppinglists idtoke: ", idtoken)
                $.ajax({
                    data: "GET",
                    url: "/sharedshoppinglists",
                    data: {
                        idtoken: idtoken
                    },
                    success(res) {
                        console.log("Geteilte Einkaufslisten");
                    },
                    error(err) {
                        console.error("/sharedshoppinglists error:", err);
                    }
                });
            }).catch((error) => console.error("Get id token client error: ", error));
        } else {
            console.log("Check Auth error", user)
        }
    });
};

function loeschen() {
    $(".trash").click(function () {

        let card = $(this).closest(".card");
        let id = card.attr("id");

        // console.log(id);

        $.ajax({
            type: "DELETE",
            url: "/shoppinglist",
            data: {
                sl_id: id
            },
            success(res) {
                console.log("card gelöscht");
                card.remove();
            },
            error(err) {
                console.log("error");
            }
        });

    });
};

function lala() {
    $(".groupadd").click(function () {
        let getid = $(this).closest('.shoplistid');
        let id = getid.attr('id');
        console.log(id);
        globaleAddZwischenID = id;  
    });
}

function gruppenhinzu() {
    $(".gruppenadd").click(function () {

        let name = $("#groupname").val();
        let color = $("input:checked").val();
        // $("#ListenDetailAdd").modal("hide");
        console.log(globaleAddZwischenID);

        firebase.auth().onAuthStateChanged(async function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {

                    $.ajax({
                        type: "POST",
                        url: "/group",
                        data: {
                            idtoken:idtoken,
                            sl_id: globaleAddZwischenID,
                            name: $("#groupname").val(),
                            color: $("input:checked").val(),
                            hidden: false
                        },
                        success(res) {
                            
                            console.log(res);
                            $("input:checked").val("");
                            $("#groupname").val("");
                            $(".ListenDetailAdd").modal("hide");

                                $(".gruppeninhalt").append(`<div class="col-md-6 col-lg-4 shoplisteid" id="${globaleAddZwischenID}">
                        <div class="card mb-3 groupid" id="" style="max-width: 18rem;background-color:#${color};">

                            <div class="card-header"><h5 class="card-title">${name}</h5><button class="btn itemadd"><i class="fas fa-plus"></i></button><button class="btn trashgroup"><i class="far fa-trash-alt"></i></button><button class="btn seemore" type="button" data-toggle="collapse" data-target="#${name}" aria-expanded="false" aria-controls="${name}"><i class="fas fa-caret-down"></i></button>
                                <div class="${name}">
                                </div>
                            </div>

                        </div></div>
                        `);

                        },
                        error(err) {
                            console.log("error");
                        }
                    });

                }).catch((error) => console.error("Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });
    });
}

function Detail() {
    $(".edit").click(function () {

        $(".cardausgabe").hide();
        $(".detailcardausgabe").show();

        let card = $(this).closest(".card");
        let id = card.attr("id");
        firebase.auth().onAuthStateChanged(async function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                    $.ajax({
                        type: "GET",
                        url: "/shoppinglist_json/" + id,
                        data: {
                            idtoken: idtoken
                        },
                        success(res) {
                            console.log(res)
                            console.log("/myshoppinglists inside idtoken: ", idtoken)
                            $.ajax({
                                type: "GET",
                                url: "/myshoppinglists",
                                data: {
                                    idtoken: idtoken
                                },
                                success(result) {
                                    // var idtoken = getIdTokenGoogle()
                                    $.ajax({
                                        type: "GET",
                                        url: "/userinfo_json",
                                        data: {
                                            idtoken: idtoken
                                        },
                                        success(data) {
                                            let userinfo = "some info"
                                            console.log(userinfo);

                                            const neu = result.filter(obj => obj.sl_id === id);

                                            var link = "/dash/" + idtoken;

                                            $(".kopf").attr("style", `background-color:#${neu[0].color}`);

                                            console.log(neu[0].color);

                                            $(".card-header").append(`<div class="shoplistid" id="${id}">
                                        <a href="${link}" style="left: 5px; margin-top: -50px;color: black;">
                                            <i class="fas fa-caret-left"></i>
                                        </a>
                                        <button class="btn groupadd" data-toggle="modal" data-target=".ListenDetailAdd"><i class="fas fa-plus"></i></button>
                                        <h1 class="text-center">
                                            ${neu[0].name}
                                        </h1></div>
                                    `);
                                            for (let i = 0; i < res.groups.length; i++) {
                                                const el = res.groups[i];
                                                $(".gruppeninhalt").append(`<div class="col-md-6 col-lg-4 shoplisteid" id="${res.sl_id}">
                                        <div class="card mb-3 groupid ${el.group_id}" id="${el.group_id}" style="max-width: 18rem;background-color:#${el.color};">

                                            <div class="card-header">
                                                <h5 class="card-title">${el.name}</h5>
                                                <button class="btn itemadd"><i class="fas fa-plus"></i></button>
                                                <button class="btn trashgroup"><i class="far fa-trash-alt"></i></button>
                                                <button class="btn seemore" type="button" data-toggle="collapse" data-target="#${el.name}" aria-expanded="false" aria-controls="${el.name}"><i class="fas fa-caret-down"></i></button>
                                                <div class="${el.name}">
                                                </div>
                                            </div>

                                        </div></div>
                                        `);
                                                for (let x = 0; x < el.content.length; x++) {
                                                    const el2 = el.content[x]
                                                    $(`.${el.name}`).append(`<div class="collapse" id="${el.name}">
                                                    <div class="card itemcard" style="background-color: transparent; ">
                                                    <div class="card-body">
                                                    ${el2.name}${el2.count}
                                                  </div>
                                                    </div>`);
                                                }
                                            }
                                            lala();
                                            gruppenhinzu();
                                            ItemAdden();
                                            groupdelete();
                                        },
                                        error(err) {
                                            console.log("Detail error userinfo_json: ", err);
                                        }
                                    })
                                },
                                error(err) {
                                    console.log("Detail error myshoppinglists: ", err);
                                }
                            });
                        },
                        error(err) {
                            console.log("Detail error shoppinglist_json: ", err);
                        }
                    });
                }).catch((error) => console.error("Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });
    });
};

function ItemAdden() {
    $(".itemadd").click(function () {

        let getslid = $(this).closest('.shoplisteid');
        let slid = getslid.attr('id');
        console.log(slid);
        let getgrid = $(this).closest('.groupid');
        let grid = getgrid.attr('id');
        globalegraddid = grid;
        globaleAddZwischenID = slid;
        $('.GroupItemAdd').modal('show');

        // firebase.auth().onAuthStateChanged(async function (user) {
        //     if (user) {
        //         firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
        //             $.ajax({
        //                 type: "GET",
        //                 url: "/shoppinglist_json/" + id,
        //                 data: {
        //                     idtoken: idtoken
        //                 },
        //                 success(result) {

        //                     console.log(result);

        //                     for (let i = 0; i < result.groups.length; i++) {
        //                         const el = result.groups[i];
                                
        //                         $(".custom-select-groups").append(`
        //                   <option class="select" value="${el.group_id}">${el.name}</option>
        //                 `);
        //                     }

        //                 },
        //                 error(err) {
        //                     console.log(err);
        //                 }
        //             });
        //         }).catch((error) => console.error("Get id token client error: ", error));
        //     } else {
        //         console.log("Check Auth error", user)
        //     }
        // });
    });
}

$(".itemhinzu").click(function () {

    var name = $('#itemname').val();
    var zahl = $('#inputGroupSelect01').val();
    console.log(name);
    console.log(zahl);


    firebase.auth().onAuthStateChanged(async function (user) {
        if (user) {
            firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                $.ajax({
                    type: "POST",
                    url: "/item",
                    data: {
                        group_id: globalegraddid,
                        sl_id: globaleAddZwischenID,
                        name: $('#itemname').val(),
                        count: $('#inputGroupSelect01').val()
                    },
                    success(result) {
                        $('.GroupItemAdd').modal('hide');
                        console.log("post item");
                    },
                    error(err) {

                    }
                });
            }).catch((error) => console.error("Get id token client error: ", error));
        } else {
            console.log("Check Auth error", user)
        }
    });

    Detail();

});

function groupdelete() {
    $('.trashgroup').click(function () {

        let getid = $(this).closest('.shoplisteid');
        let shoplistid = getid.attr('id');
        let getid2 = $(this).closest('.groupid');
        let groupid = getid2.attr('id');

        console.log(shoplistid);
        console.log(groupid);

        $.ajax({
            type: "DELETE",
            url: "/group",
            data: {
                sl_id: shoplistid,
                group_id: groupid
            },
            success(res) {
                console.log("card gelöscht");
                $(`.${groupid}`).remove();
            },
            error(err) {
                console.log("error");
            }
        });

    });
};