angular
        .module('carfriend')
        .controller('NotificationsCtrl', NotificationsCtrl);

function NotificationsCtrl(NotificationsService, CarService, AuthService, ionicMaterialInk, LoadingService, $scope, $q, $ionicPopup, IonicClosePopupService,
        geolocationService, $filter, $timeout) {
    var vm = this;

    vm.receivedNotifications = {
        nots: {},
        cars: {},
        news: {}
    };

    vm.currentUser = AuthService.getUser();
    vm.currentCar = CarService.getCar();

    vm.getReceivedNotifications = getReceivedNotifications;
    vm.getNewNotifications = getNewNotifications;
    vm.refreshReceived = refreshReceived;
    vm.showInfo = showInfo;
    vm.thank = thank;
    vm.rate = rate;
    vm.seen = seen;

    ionicMaterialInk.displayEffect();

    $scope.$on('checkNewNotif', function () {
        checkNewNotif();
    });

    $scope.$on('getReceivedNotif', function (a, b) {
        getReceivedNotifications(b);
    });

    $scope.$on('clearNewNotif', function () {
        clearNewNotifs();
    });

    $scope.$on('refreshReceivedNotif', function () {
        refreshReceived();
    });

    /////////////////////

    function getReceivedNotifications(pageSize) {
        console.log("ziskavam staree");
        NotificationsService.getReceivedNotifications(vm.currentCar.id, 1, pageSize).then(function (results) {
            vm.receivedNotifications.nots = NotificationsService.lightFormatNotifications(results.data.data);
            if(LoadingService.isLoadingNow)
                LoadingService.completeLoad();
        });
    }
    ;

    function checkNewNotif() {
        console.log("kontrolujem nove notifikacie");
        NotificationsService.checkNewNotifications(vm.currentCar.id).then(function (results) {
            if (results.data.data.length > 0) {
                getNewNotifications();
            }
        });
    }
    ;

    function getNewNotifications() {
        console.log("stahujem nove notifikacie");
        NotificationsService.getNewNotifications(vm.currentCar.id).then(function (results) {
            vm.receivedNotifications.news = formatNotifications(results.data.data);
            $timeout(function () {
                $scope.$apply(function () {
                    seen(vm.receivedNotifications.news);
                });
            }, 500);
        });
    };

    function refreshReceived() {
        console.log("refreshReceived");
        var pageSize = 5;
        NotificationsService.getReceivedNotifications(vm.currentCar.id, 1, pageSize).then(function (results) {
            vm.receivedNotifications.nots = NotificationsService.lightFormatNotifications(results.data.data);
            clearNewNotifs();
            $timeout(function () {
                $scope.$apply(function () {
                    $scope.$emit('scroll.refreshComplete');
                });
            }, 500);

        });
    }
    ;

    function clearNewNotifs(){
        if (vm.receivedNotifications.news.length > 0)
            vm.receivedNotifications.news = {};
    };
    
    function formatNotifications(d) {
        angular.forEach(d, function (value, key) {
            if (value.situation === "clamp" && value.type === '1')
                value.situation = "Práve dostávate papuču na koleso Vášho vozidla!";
            if (value.situation === "towing" && value.type === '1')
                value.situation = "Práve Vám odťahujú vozidlo!";
            if (value.situation === "accident" && value.type === '1')
                value.situation = "Práve sa Vaše vozidlo dostalo do kolízie!";
            if (value.situation === "broken_lights" && value.type === '1')
                value.situation = "Vaše vozidlo má pokazené svetlá!";
            if (value.situation === "vagabonds" && value.type === '1')
                value.situation = "Práve sa v okolí Vášho vozidla pohybujú nebezpečné osoby!";
            if (value.situation === "theft" && value.type === '1')
                value.situation = "Vaše vozidlo sa práve snaží niekto ukradnúť!";

            if (value.situation === "parking_tickets" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla policajti kontrolujú parkovacie lístky!";
            if (value.situation === "theft" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla došlo ku krádeži!";
            if (value.situation === "clamp" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla sa rozdávajú papuče na kolesá!";
            if (value.situation === "towing" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla došlo k odťahovaniu!";
            if (value.situation === "accident" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla sa stala nehoda!";
            if (value.situation === "broken_lights" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla sú pokazené svetlá!";
            if (value.situation === "vagabonds" && value.type === '2')
                value.situation = "V blízkosti Vášho vozidla boli hlasené nebezpečné osoby!";
        });
        return d;
    }
    ;


    function checkEmpty(object) {
        return angular.isUndefined(object) || object === null || object === ''
    }
    ;

    function seen(notifs) {
        var promises = [];
        angular.forEach(notifs, function (value, key) {
            promises.push(NotificationsService.seenNotification(value.id));
        });
        $q.all(promises).then(function (res) {
            $scope.$emit('vynulujBadger');
        });
    }
    ;

    function thank(notif) {
        if (!notif.thanked)
            NotificationsService.thankNotification(notif.id).then(function (response) {
                notif.thanked = true;
            }, function () {
                notif.thanked = false;
            });
    }
    ;

    function rate(notif, obj) {
        if (!notif.rated)
            NotificationsService.rateNotification(notif.id, obj).then(function (response) {
                notif.rated = obj;
            });
    }
    ;

    function showInfo(what, data) {
        var popup;
        if (what === 1 && data !== "")
            popup = $ionicPopup.alert({
                cssClass: "photoPopup",
                template: "<img src=" + data + ">",
                buttons: []
            });

        if (what === 0 && !$filter('isEmpty')(data))
            popup = $ionicPopup.alert({
                cssClass: "photoPopup popup-vertical-buttons",
                template: "<p ng-show='" + !checkEmpty(data.rated) + "'>" + "Toto upozornenie ste už označili ako <b>" + (data.rated === 'real' ? 'skutočné' : 'falošné') + "</b>.</p>" +
                        "<p ng-show='" + data.thanked + "'>Za toto upozornenie ste už <b>poďakovali</b>.</p>",
                buttons: [{
                        text: "Real",
                        type: checkEmpty(data.rated) ? 'button-default' : "noDisplay",
                        onTap: function (e) {
                            rate(data, 'real');
                        }
                    }, {
                        text: "Fake",
                        type: checkEmpty(data.rated) ? 'button-assertive' : "noDisplay",
                        onTap: function (e) {
                            rate(data, 'fake');
                        }
                    }, {
                        text: "Poďakovať",
                        type: !data.thanked ? 'button-dark' : "noDisplay",
                        onTap: function (e) {
                            thank(data, 'fake');
                        }
                    }, {
                        text: "Zaplatiť",
                        type: "button-royal disabled",
                        onTap: function (e) {
                            e.preventDefault();
                        }
                    }]
            });

        if (what === 2 && data !== null) {
            var position = {
                    latitude: data[0],
                    longitude: data[1]
            };
            geolocationService.getCurrentLocation(position).then(function (location) {
                popup = $ionicPopup.alert({
                    cssClass: "photoPopup",
                    template: "<p>" + location[0].formatted_address + "</p>",
                    buttons: []
                });
                IonicClosePopupService.register(popup);
            });
        }
        ;

        IonicClosePopupService.register(popup);
    }
    ;
}
;
