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

function LoginCtrl($state, $rootScope, AuthService, $ionicPopup, $scope, CarService, NotificationsService) {
    var vm = this;

    vm.signin = signin;
    vm.signout = signout;

    $scope.$on("$ionicView.beforeEnter", function (scopes, states) {
        initForm();
    });

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

    function initForm() {
        vm.email = '';
        vm.password = '';
        vm.signUpState = $state.params.result;
    }
    ;

    function signin() {
        AuthService.signIn(vm.email, vm.password).then(function (data) {
            AuthService.getCurrentUserInfo().then(function (currentUser) {
                if (currentUser.userType === 'driver') {
                    CarService.all(currentUser.id).then(function (car) {
                        onLogin();
                    });
                } else
                    onLogin();
            });
        }, function (error) {
            handleError(error);
        });
    }
    ;

    function handleError(err) {
        var errorPopup;
        var message;
        var buttons = [];
        var okButtton = "button-assertive";

        if (err && err.error_description && err.error_description === "The user name or password is incorrect.") {
            message = "Zadali ste zlé nesprávne prihlasovacie údaje.";
            buttons.push({text: 'Skúsiť znova', type: okButtton});

        } else {
            message = "Nastala neznáma chyba pri prihlasovaní: " + err.data;
            buttons.push({text: 'Skúsiť znova', type: okButtton});
        }
        errorPopup = $ionicPopup.show({
            title: 'Chyba!',
            template: message,
            buttons: buttons
        });
    }
    ;

    function onLogin() {
            $rootScope.$broadcast('authorized');
            $state.go('tab.wildshield');
       }
    ;

    function signout() {
//        AuthService.signout().then(function () {
//            console.log("log out done");
//            $state.go('login');
//            $rootScope.$broadcast('logout');
//            // $state.go($state.current, {}, {reload: true});
//        });
    }
    ;

}
;