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

function NotificatorCtrl($scope, $ionicModal, NotificationsService, AuthService, Backand, $ionicPopup, $cordovaCamera, geolocationService, 
                        $timeout, CarService, ParkingService, $filter, $state) {
    var vm = this;

    vm.send = send;
    vm.makePhoto = makePhoto;
    vm.cancelGPS = cancelGPS;
    vm.cancelPhoto = cancelPhoto;
    vm.cancelArea = cancelArea;
    vm.setAreaOfParkingTickets = setAreaOfParkingTickets;
    vm.attachGPSToNotification = attachGPSToNotification;
    vm.initNewNotification = initNewNotification;
    vm.redrawArea = redrawArea;
    vm.saveParkingArea = saveParkingArea;
    vm.sendAreaNotification = sendAreaNotification;
    vm.closeModal = closeModal;
    vm.goToProfile = goToProfile;
    vm.resetApp = resetApp;
    
    
    vm.slider = {};
    vm.currentUser = AuthService.getUser();
    vm.showFinder = true;

    $scope.$on("newNotification", function (event, args) {
        vm.newNotif = true;
    });
    
    $scope.$on("$ionicView.beforeLeave", function (scopes, states) {
        vm.newNotif = false;
    });
    $scope.$on("$ionicView.enter", function (scopes, states) {
            initNewNotification();
                initCops();
    });
    
    $ionicModal.fromTemplateUrl('templates/tickets.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function (modal) {
        vm.modal = modal;
    });

    setUpSlider();

   

    ////////////
    
    function send() {
        vm.sendingNotification = true;
        vm.notification.evidenceNumber = NotificationsService.getVictimID();
        if (!vm.notification.evidenceNumber || !vm.notification.situation)
            /*nevyplnenené zakladné informácie*/
            handleMissingInformation(1);
        else {
            vm.notification.from = vm.currentUser.details.id;
            vm.notification.trust = vm.currentUser.details.trust;
            /*najst email uzivatela, ktoremu sa ide poslat upozornenie*/
            CarService.getUserByCarId(NotificationsService.getVictimID()).then(function (user) {
                if (user) {
                    /*cieľový užívateľ*/
                    vm.notification.userEmail = user;
                    /*najst blizskych vodicov (iba ak je zapnute GPS)*/
                    if (!$filter('isEmpty')(vm.notification.geo)) {
                        getNearDrivers(1000, vm.notification.geo).then(function (driversList) {
                            console.log("diverlist", driversList)
                            if (driversList && driversList.drivers && driversList.drivers.length > 0) {
                                vm.notification.drivers = driversList.drivers;
                                vm.notification.carsid = driversList.carsid;
                                /*poslat upozornenie vodicovi + okolitym vodicom*/
                            }
                            handleSending();
                        }, function () {
                            /* chyba pri hladani blizkych vodicov. Posielam iba jednemu*/
                            handleSending();
                        });
                    } else {
                        /* ak nie je zapnute GPS, tak poslat upozornenie len jdnemeu vodicovi */
                        handleSending();
                    }
                } else {
                    /*chyba.. nezname ID mieneneho uzivatela*/
                    handleMissingInformation(2);
                }
            });
        }
    }
    ;

    function handleMissingInformation(code) {
        vm.sendingNotification = false;
        if (code === 1)
            $ionicPopup.alert({
                title: 'Chýbajúce údaje: ',
                template: (!vm.notification.situation && vm.notification.evidenceNumber) ? '<p> situácia</p>' :
                        (!vm.notification.situation && !vm.notification.evidenceNumber) ? '<p> evidenčné číslo</p><p> situácia</p>' :
                        (vm.notification.situation && !vm.notification.evidenceNumber) ? "<p> evidenčné číslo</p>" : 'Nastala chyba :(',
                buttons: [{
                        text: 'Zrušiť',
                        type: 'button-dark',
                        onTap: function (e) {
                            initNewNotification();
                        }
                    }, {
                        text: '<b>Doplniť</b>',
                        type: 'button-assertive'
                    }
                ]
            });
        else
            $ionicPopup.alert({
                title: 'Nastala chyba!',
                template: '<p>Ospravedlňujeme sa, ale pri posielaní nastal problém. Pravdepodobne nie je možné identifikovať majiteľa zvoleného vozidla. \n\
                            Nasledujúce tlačidlo vyresetuje formulár a skúste akciu zopakovať</p>',
                buttons: [{
                        text: 'Čo už..',
                        type: 'button-asssertive',
                        onTap: function (e) {
                            initNewNotification();
                        }
                    }
                ]
            });
    }
    ;

    function handleSending() {
        NotificationsService.sendNotification(vm.notification).then(function (response) {
            vm.sendingNotification = false;
            vm.sendingNotificationResult = "Upozornenie poslané";
            $timeout(function () {
                $scope.$apply(function () {
                    initNewNotification();
                });
            }, 3000);
        }, function (error) {
            vm.sendingNotification = false;
            vm.sendingNotificationResult = "Pri posielaní upozornenia nastala chyba";
            $timeout(function () {
                $scope.$apply(function () {
                    initNewNotification();
                });
            }, 3000);
        });
    }
    ;

    function initNewNotification() {
        console.log("initNewNotification");
        vm.notification = {
            situation: '',
            message: '',
            photo: '',
            geo: {},
            identity: true
        };
        vm.gpsError = '';
        vm.photoError = '';
        vm.takePhoto = false;
        vm.sendGPS = false;
        vm.sendingNotification = false;
        vm.sendingNotificationResult = "Poslať upozornenie";
        $scope.$broadcast('clearSearchField');
    }
    ;
        
    function getNearDrivers(distance, point) {
        var drivers = [];
        var carsid = [];
        return ParkingService.getCarWithinPosition(distance, point).then(function (cars) {
            console.log("BLIZKE AUTA: ", cars);
            if (cars.data && cars.data.relatedObjects && cars.data.totalRows >= 1) {
                var pom = cars.data.relatedObjects.cars;
                angular.forEach(pom, function (value1, key1) {
                    /*cielovemu vodicovi neposlat aj upozornenie o blizkom nebezpecenstve*/
                    if(value1.__metadata.descriptives.user.label !== vm.notification.userEmail){
                          drivers.push(value1.__metadata.descriptives.user.label);
                          carsid.push(value1.id);
                      }
                });
                return {
                    drivers: drivers,
                    carsid: carsid
                };
            } else {
                return drivers;
            }
        });
    }; 

    function getGPSinfo(errorType) {
        var position = {};
        var location = {};
        vm.gpsAreaError = false;
        vm.gpsAtachError = false;
        
        return geolocationService.getCurrentPosition().then(function (pos) {
            position = pos.coords;
            return geolocationService.getCurrentLocation(position).then(function (loc) {
                var address_components = loc[0].address_components;
                angular.forEach(address_components, function (value1, key1) {
                    angular.forEach(value1.types, function (value2, key2) {
                        location[value2] = value1.long_name;
                    });
                });
                var results = {
                    position: position,
                    location: location
                };
                return results;
            }, function (locationErr) {
                vm.atachGPSloading = false;
                vm.areaGPSloading = false;
                return handleError(locationErr, errorType);
            });
        }, function (positionErr) {
            vm.atachGPSloading = false;
            vm.areaGPSloading = false;
            return handleError(positionErr, errorType);
        });
    }
    ;
    function handleError(err, errorType) {
        console.log("Handle GPS error: ", err, errorType);
        if (errorType === 1) 
            vm.gpsAtachError = true;
        else
            vm.gpsAreaError = true;
        
        if (err.code === 1)
                vm.gpsError = "Zapnite si GPS lokalizáciu.";
            else if (err.code === 2)
                vm.gpsError = "Nie je možné Vás lokalizovať."
            else
                vm.gpsError = "Skontrolujte GPS lokalizáciu.";      
        return {};
    }
    ;

    function attachGPSToNotification() {
        vm.atachGPSloading = true;
        getGPSinfo(1).then(function (data) {
            vm.atachGPSloading = false;
            if (!$filter('isEmpty')(data)) {
                vm.sendGPS = true;
                vm.parkingLocation = data.location;
                vm.notification.geo = data.position;
            }
            ;
        });
    }
    ;

    function cancelGPS() {
        vm.notification.geo = {};
        vm.parkingLocation = {};
        vm.sendGPS = false;
        vm.gpsAtachError = false;
        if(vm.notification.situation === 'parking_tickets')
            vm.notification.situation = '';
    };
    
    function cancelPhoto(){
        vm.notification.photo = "";
        vm.takePhoto = false;
        vm.photoError = false;
    }

    function makePhoto() {
        vm.photoError = '';
        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) {
            vm.takePhoto = true;
            vm.notification.photo = "data:image/jpeg;base64," + imageData;
        }, function (err) {
            vm.takePhoto = false;
            vm.photoError = err;
        });
    }
    ;
    
    function setAreaOfParkingTickets() {
        vm.areaGPSloading = true;
        getGPSinfo(2).then(function (data) {
              vm.areaGPSloading = false;
            if (!$filter('isEmpty')(data)) {
                openModal();
                vm.publicAlert.geo = data.position;
                var styles = [{"featureType":"water","elementType":"geometry","stylers":[{"color":"#e9e9e9"},{"lightness":17}]},{"featureType":"landscape","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffffff"},{"lightness":17}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#ffffff"},{"lightness":29},{"weight":0.2}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":18}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#ffffff"},{"lightness":16}]},{"featureType":"poi","elementType":"geometry","stylers":[{"color":"#f5f5f5"},{"lightness":21}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#dedede"},{"lightness":21}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"on"},{"color":"#ffffff"},{"lightness":16}]},{"elementType":"labels.text.fill","stylers":[{"saturation":36},{"color":"#333333"},{"lightness":40}]},{"elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"geometry","stylers":[{"color":"#f2f2f2"},{"lightness":19}]},{"featureType":"administrative","elementType":"geometry.fill","stylers":[{"color":"#fefefe"},{"lightness":20}]},{"featureType":"administrative","elementType":"geometry.stroke","stylers":[{"color":"#fefefe"},{"lightness":17},{"weight":1.2}]}]; 
                var Latlng = new google.maps.LatLng(data.position.latitude, data.position.longitude);
                var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"});
                var mapOptions = {
                    zoom: 17,
                    center: Latlng,
                    disableDefaultUI: true,
                    mapTypeControlOptions: {
                        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
                    }
                };
                vm.map = new google.maps.Map(document.getElementById("parkingTicketsMap"), mapOptions);

                vm.map.mapTypes.set('map_style', styledMap);
                vm.map.setMapTypeId('map_style');
                vm.marker = new google.maps.Marker({
                    position: Latlng,
                    map: vm.map,
                    title: 'Moja pozícia'
                });
                var area = {
                    map: vm.map,
                    radius: 60, // metrov
                    fillColor: '#F44336',
                    strokeColor: "#F44336",
                    strokeOpacity: 0.35,
                    strokeWeight: 0,
                    fillOpacity: 0.35,
                    center: vm.marker.getPosition()
                };
              vm.selectedArea = new google.maps.Circle(area);
            }
        });
    }
    ;
    
    function redrawArea() {
        vm.selectedArea.setMap(null);
        var area = {
            map: vm.map,
            radius: parseInt(vm.areaRanger),
            fillColor: '#F44336',
            strokeColor: "#F44336",
            strokeOpacity: 0.35,
            strokeWeight: 0,
            fillOpacity: 0.35,
            center: vm.marker.getPosition()
        };
        vm.selectedArea = new google.maps.Circle(area);
    }
    ;
    
    function saveParkingArea() {
        vm.searchingNearDrivers = true;
        vm.areaRanger = vm.areaRanger === null ? 60 : vm.areaRanger;
        getNearDrivers(vm.areaRanger, vm.publicAlert.geo).then(function (near) {
            vm.searchingNearDrivers = false;
            if (near && near.drivers && near.drivers.length > 0) {
                vm.publicAlert.carsid = near.carsid;
                vm.publicAlert.drivers = near.drivers;
            }       
            closeModal();
        });
    }
    ;
    
    function cancelArea(){
        initCops();
        closeModal();
    }
 
    function sendAreaNotification() {
        vm.publicAlert.from = vm.currentUser.details.id;
        vm.publicAlert.trust = vm.currentUser.details.trust;
        NotificationsService.sendAreaNotification(vm.publicAlert).then(function (response) {
            console.log(response);
            if (response.statusText === "OK") {
                initCops();
                vm.areaResult = {
                    status: true,
                    message: "Vodiči boli úspešne informovaní.",
                    icon: "ion-checkmark"
                };
            } else {
                initCops();
                vm.areaResult = {
                    done: false,
                    message: "Nastala chyba a vodiči nemohli byť informovaní.",
                    icon: "ion-close"
                };
            }
           });
    }
    ;

    function initCops(){
        vm.publicAlert = {
            geo: {},
            situation: null,
            carsid:[],
            drivers:[]
        };
        vm.areaRanger = null;
        vm.selectedArea = null;
        vm.areaResult = {};
        vm.gpsAreaError = false;
    };

    function openModal() {
        vm.modal.show();
    }
    ;
    function closeModal() {
        vm.modal.hide();
    }
    ;

    function goToProfile(profile) {
        var currentState = $state.current.name;
        return $state.go('profile', {userID: profile, from: currentState});
    }
    ;

    function setUpSlider() {
        vm.sliderOptions = {
            loop: false,
            speed: 500,
            paginationHide: true,
            pagination: "",
            spaceBetween: 100,
            direction: 'horizontal',
            onTransitionEnd: function (slider) {
                setCurrentSlide(slider.activeIndex);
                clearSlide();
            }
        };
    }
    ;

    function setCurrentSlide(index) {
        $scope.$apply(vm.slider.activeIndex = index);
        if (index === 1)
            $scope.$apply(vm.showFinder = false);
        else
            $scope.$apply(vm.showFinder = true);
    }
    ;

    function clearSlide() {
        vm.areaResult = {};
    }
    ;

    function resetApp() {
       // var username = Backand.getUsername();
        var token = Backand.getToken();
        vm.resetAppResult = "";
        if (!token) {
            setTimeout(function () {
                $scope.$apply(function () {
                    vm.resetAppResult = "Neznámy token. Presmerúvam na prihlasovanie";
                });
            }, 200);
            $timeout(function () {
                $scope.$broadcast('scroll.refreshComplete');
                $state.go('login');
            }, 2500);
        } else
            AuthService.getCurrentUserInfo().then(function (currentUser) {
                setTimeout(function () {
                    $scope.$apply(function () {
                        vm.resetAppResult = "Podarilo sa obnoviť aplikáciu.";
                    });
                }, 200);
                if (currentUser.userType === 'driver') {
                    CarService.all(currentUser.id).then(function (car) {
                        $timeout(function () {
                            $scope.$broadcast('scroll.refreshComplete');
                        }, 1500);
                    });
                } else
                    $timeout(function () {
                        $scope.$broadcast('scroll.refreshComplete');
                    }, 1500);
            });
    }
    ;
}
;