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

function BadgerCtrl(NotificationsService, CarService, AuthService, $scope) {

    var vm = this;
    vm.newNotifCounter = 0;
    vm.newMessageCounter = 0;
    vm.currentUser = {};

    loadUser();

    $scope.$on('incBadger', function (event, mass) {
        changeCounter(1, true);
        //$scope.$apply(vm.newNotifCounter = vm.newNotifCounter + mass);          
    });
    $scope.$on('desBadger', function (event, mass) {
        changeCounter(mass, false);
    });
    $scope.$on('vynulujBadger', function (event, mass) {
        vm.newNotifCounter = 0;
    });

    $scope.$on('incChatBadger', function (event, mass) {
        console.log("incChatBadger");
            changeChatCounter(1, true);
    });
    $scope.$on('vynulujChatBadger', function (event, mass) {
        console.log("vynulujChatBadger");
        vm.newMessageCounter = 0;
    });


    ///////////
    function loadUser() {
        AuthService.getCurrentUserInfo().then(function (currentUser) {
            vm.currentUser = currentUser;
            if (currentUser.userType === 'driver') {
                CarService.all(currentUser.id).then(function (car) {
                    NotificationsService.checkNewNotifications(car.id).then(function (results) {
                        vm.newNotifCounter = results.data.data.length;
                        console.log("-----------------------");
                        console.log("uzivatel: ", currentUser);
                        console.log("auto: ", car);
                        console.log("pocet novych uporozneni: ", vm.newNotifCounter);
                        console.log("-------------------------");
                    });
                });
            }
        });
    }
    ;
    
    function changeCounter(mass, raise) {
        if (raise)
            vm.newNotifCounter = vm.newNotifCounter + mass;
        else
            vm.newNotifCounter = vm.newNotifCounter - mass;
    }
    ;

    function changeChatCounter(mass, raise) {
        if (raise)
            vm.newMessageCounter = vm.newMessageCounter + mass;
        else
            vm.newMessageCounter = vm.newMessageCounter - mass;
    }
    ;
}