var id;

$(document).ready(function () {

    M.AutoInit();
    //initialize all modals           
    $('.modal').modal({
        dismissible: false
    });


    $('.materialboxed').materialbox();
    $('.fixed-action-btn').floatingActionButton();


    if ($(window).width() > 600) {
        //large     
        $(".col").css("height", "100%");
    } else {
        //small    
        $(".col").css("height", "50%");
    }

    $("#modal1").modal("open");


    $(".btn-analyze").click(function () {
        analyzeUploaded();
    });

    //AJAX

    // 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);


    updateUser();
    testSearch();



    function movePurchases(text) {
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                    $.ajax({
                        type: "POST",
                        url: "/dones",
                        data: {
                            idtoken: idtoken,
                            sl_id: id,
                            billcontent: text
                        },
                        success(result) {
                            console.log(result);
                            window.location.href = "/dash/" + idtoken
                        },
                        error(err) {
                            console.error("Error: " + err);
                        }
                    });
                }).catch((error) => console.error("Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });
    }

    $(".test").click(function () {
        //movePurchases();
        getAllShoppinglists();
    });

    $(document).on("click", ".btndash", function () {
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                    window.location.href = "/dash/" + idtoken
                }).catch((error) => console.error("Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });
    });

    function analyzeUploaded() {

        $("#modalEND").modal("open");

        var img = document.getElementById("blah");

        Tesseract.recognize(img).progress((progress) => {

            if (progress.status == "recognizing text") {
                loading = true;
            }
        }).then((result) => {
            loading = false;
            console.log(result.text);
            movePurchases(result.text);
            $(".determinate").css("width", "0%");
        });
    }

    setInterval(updateProgress(), 500);

    function updateProgress(percent) {
        if (loading == true) {
            $(".determinate").css("width", progress.progress * 100 + "%");
        }

    }

    function updateUser() {
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function (idtoken) {
                    $.ajax({
                        type: "POST",
                        url: "/user",
                        data: {
                            idtoken: idtoken,
                            message_id: "msgtest"
                        },
                        success() {
                            console.log("USer updated");
                        },
                        error(err) {
                            console.error("Error: " + err);
                        }
                    });
                }).catch((error) => console.error("Get id token client error: ", error));
            } else {
                console.log("Check Auth error", user)
            }
        });
    }

    function testSearch() {

        $.ajax({
            type: "GET",
            url: "/users?search=Luk",
            success(data) {
                console.log("Users ", data);
            },
            error(err) {
                console.error(err);
            }
        });
    }

    getAllShoppinglists();

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

                            $(".preloader-wrapper").css("display", "none");
                            for (let item of data) {
                                $(".output").append("<a id='" + item.sl_id + "' class='collection-item'>" + item.name + "</a>")
                            }

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

    $(document).on("click", ".collection-item", function () {
        id = $(this).closest("a").attr("id");

        $(".active").removeClass("active");

        $(this).addClass("active");
    });

    $(".btncont").click(function () {
        run([{
            y: 100
        }, {
            y: 0
        }], $(".r1"));
    });

    /*$.ajax({
        type: "POST",
        url : "/movedoneitem",
        data : {
            sl_id : 'hcMssjPd',
            group_id: 'hcMssjPd',
            item_id: 'EHmY4ymD'
        }
    })*/

    function run(v, elem) {
        //Reverse the array
        var reversed = JSON.parse(JSON.stringify(v)).reverse();

        $(v[0]).animate(v[1], {
            //The speed the element moves - lower is faster
            duration: 500,
            step: function (val) {
                //Adding the transform to your element
                elem.css("transform", `translateY(${val}%)`);
            }
        })
    };

    $(".opt1").click(function () {
        run([{
            y: 0
        }, {
            y: -100
        }], $(".r1"))

        run([{
            y: 0
        }, {
            y: -100
        }], $(".r2"));
        //$("#modal2").modal("open");
    });

    $(".opt2").click(function () {
        // $('.row').animate({'margin-top': '-100%'}, 1000);
    });

});

var loading = false;

/*function analyze() {
    var img = document.getElementById("canvas").toDataURL();

    Tesseract.recognize(img).progress((progress) => {

        if (progress.status == "recognizing text") {
           loading = true;
        }
    }).then((result) => {
        loading = false;
        $(".output").text(result.text);
        $('.modal').modal("open");

        $(".determinate").css("width", "0%");
    });
}
*/