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

function PerformanceCtrl(NotificationService, CarService, AuthService, $q, LoadingService, $scope, Backand, $ionicPopup, IonicClosePopupService, geolocationService, $filter) {
    var perform = this;
    perform.angular = angular
    perform.notifications = [];

    $scope.$on("$ionicView.enter", function (scopes, states) {
        console.log("Enter to notif view");
        perform.user = AuthService.returnUser();
        console.log("Notif view user", perform.user);
        getNotification();
    });


    Backand.on('items_updated', function (data) {
        //Get the 'items' object that have changed
        console.log(data);
    });

    function getNotification() {
        console.log("getting notifications");
        if (perform.user.details.userType == 'driver') {
            CarService.getUserCars(perform.user.details.id).then(function (userCar) {
                console.log("getting driver cars: ", userCar);
                perform.car = userCar;
                $q.all([NotificationService.getSendNotifications(perform.user.details.id),
                    NotificationService.getReceivedNotifications(userCar.id)]).then(function (results) {
                    console.log("got driver notifications ", results);
                    LoadingService.completeLoad();
                    perform.loading = false;
                    if (results.length != 2) {
                        console.log("Smt happend")
                    } else {
                        perform.notifications.send = results[0].data.data;
                        perform.notifications.received = results[1].data.data;
                        perform.notifications.cars = results[0].data.relatedObjects.cars;
                        console.log(perform.notifications.send)
                    }
                }, function (err) {
                    console.log("error-got driver notifications", err);
                    LoadingService.completeLoad();
                    perform.loading = false;
                })
            }, function (error) {
                console.log("err-getting driver cars");
            })
        } else {
            NotificationService.getSendNotifications(perform.user.details.id).then(function (res) {
                console.log("got user notifications", res);
                LoadingService.completeLoad();
                perform.loading = false;
                console.log("nacitavam poslane notifikacie usera: ", res);
                if (res.data.data.length != 0) {
                    console.log("user poslal minimalne 1 notifikaciu");
                    perform.notifications.send = res.data.data;
                    perform.notifications.cars = res.data.relatedObjects.cars;
                }
            });
        }
    }
    ;

    perform.showDetails = function (notif, car) {
        var position;
        var popup;
        var ratePopup;
        var datetime;
        getLocation(notif.lat, notif.lang).then(function (val) {
            position = val;
            datetime = $filter('date')(notif.datetime, "dd.MM.yy HH:mm");
            if (car) {
                //send
                popup = $ionicPopup.alert({
                    title: " <div class='row'>" +
                            "<div class='col col-10' style='display: flex;justify-content: flex-end;align-items: center;'>" +
                            "<i class='ion ion-log-out' style='font-size:1.3rem !important'></i>" +
                            "</div>" +
                            "<h4 class='col col-80'>Notification details</h4>" +
                            "<div class='col col-10' style='display: flex;justify-content: flex-end;align-items: center;'>" +
                            "<i class='ion ion-log-out' style='font-size:1.3rem !important'></i>" +
                            "</div>" +
                            "</div>"
                    ,
                    subTitle: datetime + " | " + (notif.rated ? notif.rated : 'not rated') + " | " + (notif.thanked ? "thanked" : 'not thanked'),
                    scope: $scope,
                    cssClass: "notificationPopup noButtons",
                    template: "<img src=" + (notif.photo ? notif.photo : 'img/unavailable.png') + ">" +
                            "<h4><i class='ion-android-car' style='font-size:1.2rem !important'> </i> <a href='#/profile/" + perform.getCar(notif.to).user + "'>" + car.evidenceNumber + "</a></h4>" +
                            "<h5><i class='ion ion-clipboard' style='font-size:0.9rem !important'> </i> " + notif.situation + "</h5>" +
                            "<p style='font-size:0.7rem; width: 150px;line-height: 11px;'>\n\
                                                                        <i class='ion ion-ios-paperplane-outline' style='font-size:0.7rem !important'> </i> " + position +
                            "</p>" +
                            "<div class='mess' ng-show='" + !perform.checkEmpty(notif.message) + "'>" +
                            "<p><i class='ion ion-ios-email-outline' style='font-size:1rem !important'> </i> " + notif.message + "</p>" +
                            "</div>",
                    buttons: [{}]
                })
            } else {
                //received
                popup = $ionicPopup.alert({
                    title: " <div class='row'>" +
                            "<div class='col col-10' style='display: flex;justify-content: flex-end;align-items: center;'>" +
                            "<i class='ion ion-log-in' style='font-size:1.3rem !important'></i>" +
                            "</div>" +
                            "<h4 class='col col-80'>Notification details</h4>" +
                            "<div class='col col-10' style='display: flex;justify-content: flex-end;align-items: center;'>" +
                            "<i class='ion ion-log-in' style='font-size:1.3rem !important'></i>" +
                            "</div>" +
                            "</div>"
                    ,
                    subTitle: datetime + " | " + (notif.rated ? notif.rated : 'not rated') + " | " + (notif.thanked ? "thanked" : 'not thanked'),
                    cssClass: "notificationPopup",
                    template: "<img src=" + (notif.photo ? notif.photo : 'img/unavailable.png') + ">" +
                            "<h5><i class='ion ion-clipboard' style='font-size:0.9rem !important'> </i> " + notif.situation + "</h5>" +
                            "<p style='font-size:0.7rem; width: 150px;line-height: 11px;'>\n\
                                                                        <i class='ion ion-ios-paperplane-outline' style='font-size:0.7rem !important'> </i> " + position +
                            "</p>" +
                            "<div class='mess' ng-show='" + !perform.checkEmpty(notif.message) + "'>" +
                            "<p><i class='ion ion-ios-email-outline' style='font-size:1rem !important'> </i> " + notif.message + "</p>" +
                            "</div>",
                    buttons: [{
                            text: 'Rate',
                            type: perform.checkEmpty(notif.rated) ? 'button-default' : "noDisplay",
                            onTap: function (e) {
                                ratePopup = $ionicPopup.show({
                                    cssClass: "notificationPopup",
                                    title: 'Rate this notification',
                                    buttons: [{
                                            text: "Real",
                                            type: "button-default",
                                            onTap: function (e) {
                                                perform.rate(notif, 'real');

                                            }
                                        }, {
                                            text: "Fake",
                                            type: "button-assertive",
                                            onTap: function (e) {
                                                perform.rate(notif, 'fake');

                                            }
                                        }]

                                });
                            }
                        }, {
                            text: "Say thank",
                            type: perform.checkEmpty(notif.thanked) ? 'button-dark' : "noDisplay",
                            onTap: function (e) {
                                perform.thank(notif);
                            }
                        }, {
                            text: 'Buy a coffe',
                            type: 'button-assertive',
                            onTap: function (e) {

                            }
                        }]
                })
            }
            IonicClosePopupService.register(ratePopup);
            IonicClosePopupService.register(popup);
        })


    };

    perform.checkEmpty = function (what) {
        return angular.isUndefined(what) || what === null || what === ''
    }


    function getLocation(lat, lang) {
        var deferred = $q.defer();
        if (lat && lang) {
            var position = {
                coords: {
                    latitude: '',
                    longitude: ''
                }
            }
            position.coords.latitude = lat;
            position.coords.longitude = lang;
            geolocationService.getCurrentLocation(position).then(function (location) {
                deferred.resolve(location[0].formatted_address);
            }, function (err) {
                deferred.reject(err);
            })

        } else {
            deferred.resolve("unknown location");
        }
        return deferred.promise;
    }

    perform.doRefresh = function () {
        getNotification();
        $scope.$broadcast('scroll.refreshComplete');

    };
    perform.getCar = function (to) {
        return perform.notifications.cars[to];
    }

    perform.slider = {};
    perform.sliderOptions = {
        loop: false,
        speed: 900,
        paginationHide: true,
        pagination: "",
        spaceBetween: 500,
        initialSlide: 1,
        onTransitionEnd: function (slider) {
            setCurrentSlide(slider.activeIndex);
        },
    }

    function setCurrentSlide(index) {
        $scope.$apply(perform.slider.activeIndex = index);
    }

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

    perform.rate = function (notif, what) {
        if (!notif.rated)
            NotificationService.rateNotification(notif.id, what).then(function (response) {
                notif.rated = what;
                $scope.$emit('desBadger', 1);
            })
    }
    LoadingService.startLoad();
    perform.loading = true;
}