var myapp = angular.module('QueComenzi',[]);


myapp.controller('simpleController', function($scope, $http) {

    $scope.getComenzi = function () {
        setInterval(function () {
            //$http.get('getData.php').then(successCallback, errorCallback);

            $http.post('getData.php',{
                whatToGet: 'comenzi'
            }).then(successCallback, errorCallback);
           // $scope.initMap();

        }, 2000);

        $http.post('getData.php',{
            whatToGet: 'comenzi'
        }).then(successCallback, errorCallback);

        function successCallback(response){
            $scope.dataBack = response.data.response;

if (($("#tabel_comenzi tbody tr:nth-child(1) .idComanda").length > 0) && (response.data.response[0] != undefined)) {
            var idComTabel = $("#tabel_comenzi tbody tr:nth-child(1) .idComanda").text();
             var idComDB = response.data.response[0].ID;


/*
    function dataDiffRow(whatRow) {
        var currTR = $("tr[data-id="+whatRow+"]");
        var currStatus = currTR.find("th.comStatus").text();


        if (parseInt(currStatus) == 0) {
            console.log("CHECKING!");
           // console.log(lastIDEle2);
            //var lastIDEle = $("tr[data-id="+whatRow+"] th.dataAddVal");
            var currentdate = (new Date()).toLocaleTimeString("ro-RO");
            var lastIDEle = currTR.find("th.dataAddVal");
            var currEstimation = parseInt(currTR.find("th.comEst").text().split("")[0]);

            var lastIDText = lastIDEle.text();

            var hourID = parseInt(lastIDText.split(":")[0]);
            var minID = parseInt(lastIDText.split(":")[1]);

            //var hourIntID = parseInt(hourID);
            //var minIntID = parseInt(minID);

            var nowHours = parseInt(currentdate.split(":")[0]);
            var nowMins = parseInt(currentdate.split(":")[1]);


            console.log(nowHours+":"+nowMins);
            if ((currEstimation + minID) < 60) {
                if (hourID == nowHours) {
                    console.log("hours equal");
                    if (nowMins > (currEstimation + minID)) {
                        console.log("notifiy!!!");
                        //$scope.notifyMe();
                        //console.log("Finished!!!!");
                    }
                }
            } else {
                console.log("else");
                var minDiff = (currEstimation + minID - 60);
                if (nowMins > minDiff) {
                    //$scope.notifyMe();
                    console.log("notify diff hour!!!!");
                }
            }






            //console.log("from function:" + currHours +":" + currMins);
/!*            if (minID < 46) {
                console.log("scadem din  ora CURENTA");
            } else if (minID > 45 && minID < 61) {
                console.log("scadem din URMATOAREA ora");
            }*!/



        }

        //console.log((minID));
    }
*/

    function dataDiff(whatRow) {

        var currTR = $("#tabel_comenzi tr[data-id="+whatRow+"]");
        console.log(currTR);
        var currStatus = currTR.find("th.comStatus").text();


        if (parseInt(currStatus) == 0) {
            console.log("CHECKING!");
            var currentdate = (new Date()).toLocaleTimeString("ro-RO");
            var currHour = currentdate.split(":")[0];
            var currMins = currentdate.split(":")[1];
            var currSecs = currentdate.split(":")[2];

            var lastIDEle = currTR.find("th.dataAddVal");
            var currEstimation = parseInt(currTR.find("th.comEst").text().split(" ")[0]);

            var lastIDText = lastIDEle.text();

            var hourID = parseInt(lastIDText.split(":")[0]);
            var minID = parseInt(lastIDText.split(":")[1]);
            var secID = parseInt(lastIDText.split(":")[2]);



            var currTimeDate = new Date(Date.UTC(2018, 1, 1, (currHour - 2), currMins, currSecs));


            console.log(currEstimation);
            console.log(minID);
            var timeOrder = new Date(Date.UTC(2018, 1, 1, (hourID - 2), (minID + currEstimation) , secID));
            localDateString = currTimeDate.toLocaleDateString("ro-RO");
            localTimeString = timeOrder.toLocaleTimeString("ro-RO");

            console.log("Order time" + timeOrder);
            console.log("Current time" + currTimeDate);


            // console.log(localTimeString);


            if (currTimeDate >= timeOrder) {
                currTR.addClass("text-danger");
                $scope.danger = function () {
                  return "text-danger";
                };

                //currTR.css("color", "red");
                console.log("true! time elapsed");
            }


        }

        var timeNow = (new Date()).toLocaleTimeString("ro-RO");
        console.log("TimeNow: "+ timeNow);

        // GMT + 2 !!!!!
        var date = new Date(Date.UTC(2013, 1, 1, 10, 0, 0));
        var options = {
            weekday: "long", year: "numeric", month: "short",
            day: "numeric", hour: "2-digit", minute: "2-digit"
        };


    }


    //dataDiff(77);

    // console.log("71:");  dataDiffRow(71);
    //console.log("72:");  dataDiffRow(72);

/*$("#tabel_comenzi tbody tr").each(function () {
   dataID = $(this).attr("data-id");
   console.log(dataID);
   dataDiffRow(dataID);
});*/

var attrID = $("#tabel_comenzi tbody tr:first-child").attr("data-id");
    console.log(attrID);


/*    $("#tabel_comenzi tbody tr").each(function () {
       var comStatus = parseInt($(this).find(".comStatus").text())
       if (comStatus == 0) {
           dataDiff(attrID);
       } else {
           if($(this).hasClass("text-danger")) {
               $(this).removeClass("text-danger");
           }
       }
    });*/

            //console.log(response.data.response[0].ID);
            if (parseInt(idComDB) > parseInt(idComTabel)) {
                $scope.notifyMe();
                $scope.initMap();
                //console.log("Different");
            }
            //console.log("id==== " +id);
            //console.log();
}
        }


        function errorCallback(error){
            //error code
            console.log(error);
        }



    };

    $scope.getUsers = function () {
            $http.post('getData.php',{
                whatToGet: 'users'
            }).then(successCallback, errorCallback);

        function successCallback(response){
            $scope.Users = response.data.response;
/*            for (i=0;i<response.data.response.length;i++) {
                console.log(i);
            }*/
            //console.log(response.data.response);
        }
        function errorCallback(error){
            console.log(error);
        }
    };


    $scope.getCoffees = function () {
        $http.post('getData.php',{
            whatToGet: 'coffees'
        }).then(successCallback, errorCallback);

        function successCallback(response){
            $scope.coffees = response.data.response;
            //console.log(response.data.response);
        }
        function errorCallback(error){
            console.log(error);
        }
    };

    $scope.UpdateOrder = function () {

        if ($(".tbl_apply").is(":checked")) {
            var id = $(".tbl_id").text();
            console.log("check!" + id);
            $http.post('updateOrder.php',{
                comID: id
            }).then(successCallback, errorCallback);
        }



        function successCallback(response){
            //$scope.coffees = response.data.response;
            $scope.getComenzi();
            console.log(response.data);
        }
        function errorCallback(error){
            console.log(error);
        }
    };




    $(document).on("click", "#tabel_comenzi th",function () {
       var id = $(this).parent().attr("data-id");
       $(".tbl_id").text(id);
       console.log(id);
    });

    $scope.comenziSee = true;
    $scope.userSee = false;
    $scope.coffeeSee = false;
    $scope.mapSee = false;


    $scope.whatToShow = function (what) {
        if (what == "comenzi") {
            $scope.comenziSee = true;
            $scope.userSee = false;
            $scope.coffeeSee = false;
            $scope.mapSee = false;
        }


        if (what == "users") {
            $scope.userSee = true;
            $scope.comenziSee = false;
            $scope.coffeeSee = false;
            $scope.mapSee = false;
        }


        if (what == "coffees") {
            $scope.coffeeSee = true;
            $scope.comenziSee = false;
            $scope.userSee = false;
            $scope.mapSee = false;
        }



        if (what == "maps") {
            $scope.mapSee = true;
            $scope.comenziSee = true;
            $scope.coffeeSee = false;
            $scope.userSee = false;
        }
        //$scope.seeComenzi = true;

        return true;
    };




    $scope.initMap = function() {
        //setTimeout(function () {



        $http.post('getData.php',{
            whatToGet: 'comenzi'
        }).then(successCallback, errorCallback);



        function successCallback(response){
            $scope.Users = response.data.response;

            //var locs = [['asd','asd'], ['bsa', 'bsa']];
            var responseLength = response.data.response.length;
            var locs = new Array();

            //locs.push(new Array(responseLength));

            //console.log(locs);

/*            locs[0][0] = 0;
            locs[0][1] = 1;
            locs[0][2] = 2;
            locs[1][2] = 12;*/
            console.log(locs.length);
            for (i=0;i<responseLength;i++) {
                var tel = response.data.response[i].Telefon;
                var nume = response.data.response[i].Nume;
                var denumire = response.data.response[i].denumire;

                var lat = ["<div>"+nume+"</br>"+tel+"</div><div>"+denumire+"</div>",parseFloat(response.data.response[i].Latitude),parseFloat(response.data.response[i].Longitude),parseInt(i)];
                //console.log(lat[0]);
                //locs[i] = response.data.response[i].Latitude;


                locs.push(lat);

                //console.log(response.data.response[i].Latitude +", " + response.data.response[i].Longitude);
            }
            //console.log(response.data.response);


            var locations = [
                ['<strong style="font-size: 20px;">Bondi Beach</strong>', 44.4296946, 26.155822, 4],
                ['Coogee Beach', 44.4297136, 26.0558251, 5],
                ['Cronulla Beach', 44.4297205, 26.0458077,3],
                ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
                ['Maroubra Beach', -33.950198, 151.259302, 1]
            ];

            console.log(locations);
            //console.log()
            console.log("locs\n");
            console.log(locs);


            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 13,
                center: new google.maps.LatLng(44.4296946, 26.155822),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var infowindow = new google.maps.InfoWindow();

            var marker, i;

            for (i = 0; i < locs.length; i++) {
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locs[i][1], locs[i][2]),
                    map: map
                });

                marker.setMap(map);

                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(locs[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }











        }
        function errorCallback(error){
            console.log(error);
        }








/*

        var uluru = {lat: 44.440744, lng: 26.092698};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 16,
            center: uluru
        });


        var contentString = "hello";

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: uluru,
            map: map,
            title: 'Uluru (Ayers Rock)'
        });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });*/



        //}, 1000);

    } // end map function



    document.addEventListener('DOMContentLoaded', function () {
        if (!Notification) {
            alert('Desktop notifications not available in your browser. Try Chromium.');
            return;
        }

        if (Notification.permission !== "granted")
            Notification.requestPermission();
    });

    $scope.notifyMe = function() {
        if (Notification.permission !== "granted")
            Notification.requestPermission();
        else {
            var notification = new Notification('Comanda noua!', {
                icon: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTHZPgcJnrH7V9JpS762KUkP1YDf5a8-PhEJfi1fwSUX4ftn2nc',
                body: "O noua comanda a fost plasata!",
            });

            var audio = new Audio('/android/assets/audio/newOrderNaruto.mp3');
            audio.play();

            notification.onclick = function () {
                //window.open("https://stackoverflow.com/a/13328397/1269037");
            };

        }

    }



    //initMap();



});