angular
        .module('carfriend')
        .controller('OptionsCtrl', optionsCtrl);

function optionsCtrl(AuthService, $ionicPopup, CarService, IonicClosePopupService, NotificationsService, UsersService, $scope, $filter, $ionicHistory, 
                $state, $cordovaCamera, LoadingService) {
    var vm = this;

    var pageSize = 4;
    vm.emailSetting = emailSetting;
    vm.uploadPhoto = uploadPhoto;
    vm.signout = signout;
    vm.doRefresh = doRefresh;
    vm.loadMore = loadMore;
    vm.showInfo = showInfo;
    vm.emailSettingError = false;
    vm.myActivity = {
        nots: {},
        cars: {},
        activity: null
    };

    $scope.$on("$ionicView.enter", function () {
        loadData();
        if (vm.myActivity.activity === null)
            loadMore();
        else
            doRefresh();
    });

    $scope.$on("newNotification", function (event, args) {
        vm.newNotif = true;
    });
    $scope.$on("$ionicView.beforeLeave", function (scopes, states) {
        vm.newNotif = false;
    });
    
    $scope.$on("$ionicView.loaded", function (scopes, states) {
        LoadingService.startLoad();
    });


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

    function loadData() {
        vm.currentUser = AuthService.getUser();
        vm.car = CarService.getCar();
    };

    function emailSetting() {
        UsersService.emailSetting(vm.currentUser.details.id, vm.currentUser.details.emailNotifications).then(function () {
            vm.emailSettingError = false;
        }, function () {
            vm.emailSettingError = true;
        });
    }
    ;
    
      function uploadPhoto() {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 300,
            targetHeight: 300,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false,
            allowEdit: false,
            correctOrientation: true
        };
        $cordovaCamera.getPicture(options).then(function (imageData) {
            var fotka = "data:image/jpeg;base64," + imageData;
            UsersService.update(vm.currentUser.details.id, {photo: fotka}).then(function (suc) {}, function (err) {
                $ionicPopup.alert({
                    title: "Chyba!",
                    template: "Nastala chyba pri posielaní dát.",
                    buttons: [{
                            text: '<b>OK</b>',
                            type: 'button-assertive'
                        }]
                });
            });
        }, function (err) {
            $ionicPopup.alert({
                title: "chyba!",
                template: "Nastala chyba pri práci s kamerou.",
                buttons: [{
                        text: '<b>OK</b>',
                        type: 'button-assertive'
                    }]
            });
        });
    }
    ;

    function signout(){
        AuthService.signout().then(function(){
            $ionicHistory.clearCache();
            $ionicHistory.clearHistory();
            $state.go('login');
        });
    };

    function calculateNumberOfSendNotifications() {
        vm.dataLoading = true;
        return NotificationsService.getSendNotifications(vm.currentUser.details.id, 1, 0).then(function (notifs) {
            return notifs.data.totalRows;
        });
    }
    ;

    function loadMore() {
        calculateNumberOfSendNotifications().then(function (d) {
            vm.myActivity.activity = d;
            if (canILoadMore(vm.myActivity.activity, vm.myActivity.nots.length)) {
                vm.loadedDataStatus = "Načítaj ďalšie";
                if (!$filter('isEmpty')(vm.myActivity.nots)) {
                    pageSize = vm.myActivity.nots.length + 3;
                }
                NotificationsService.getSendNotifications(vm.currentUser.details.id, 1, pageSize).then(function (notifs) {
                    var pom = NotificationsService.lightFormatNotifications(notifs.data.data);
                    vm.myActivity.cars = notifs.data.relatedObjects.cars;
                    vm.myActivity.nots = pom;
                    vm.dataLoading = false;
                    if (LoadingService.isLoadingNow)
                        LoadingService.completeLoad();
                });
            } else {
                vm.dataLoading = false;
                vm.loadedDataStatus = "To je všetko :)";
            }
        });
    }
    ;

    function canILoadMore(total, current) {
        if (total === null)
            return false;
        if (total <= current)
            return false;
        else
            return true;
    }
    ;

    function getCar(id) {
        return vm.myActivity.cars[id];
    }
    ;

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

    function showInfo(data) {
        var popup;
        var nearNotif;
        nearNotif = data.type === "2" ? true : false;
        console.log(data.type, nearNotif);
        if (!$filter('isEmpty')(data))
            popup = $ionicPopup.alert({
                cssClass: "photoPopup",
                template: '<h2>Upozornenie pre ' + getCar(data.to)["evidenceNumber"] + "</h2>" +
                         "<p ng-if='" +nearNotif +"'>Upozornenie, ktoré nebolo poslané priamo ale na základe polohy.</p>" +
                        "<p>" + "Upozornenie <b>" + (data.seen ? 'už bolo zobrazené' : 'ešte nebolo zobrazené') + "</b>.</p>" +
                        "<p ng-if='" + !checkEmpty(data.rated) + "'>" + "Toto upozornenie vodič označil ako <b>" + (data.rated === 'real' ? 'skutočné' : 'falošné') + "</b>.</p>" +
                        "<p ng-if='" + data.thanked + "'>Za toto upozornenie Vám vodič <b>poďakoval</b>.</p>",
                buttons: []
            });
        IonicClosePopupService.register(popup);
    }
    ;

    function doRefresh() {
        AuthService.getCurrentUserInfo().then(function () {
            loadData();
        });
        calculateNumberOfSendNotifications().then(function (d) {
            vm.myActivity.activity = d;
            NotificationsService.getSendNotifications(vm.currentUser.details.id, 1, 4).then(function (notifs) {
                var pom = NotificationsService.lightFormatNotifications(notifs.data.data);
                vm.myActivity.cars = notifs.data.relatedObjects.cars;
                vm.myActivity.nots = pom;
                $scope.$broadcast('scroll.refreshComplete');
                vm.loadedDataStatus = "Načítaj ďalšie";
                vm.dataLoading = false;

            });
        });
    }
    ;

}