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

function SignUpCtrl($scope, $filter, $state, AuthService, CarService, $ionicPopup, ColorService, ionicMaterialInk) {
    var vm = this;
    ionicMaterialInk.displayEffect();

    vm.colorsOffer = ColorService.getColors();
    vm.signUp = signUp;
    vm.selectUserType = selectUserType;
    vm.isActive = isActive;
    vm.checkInputs = checkInputs;

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

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

    function initForm() {
        vm.userType = "";
        vm.email = "";
        vm.password = "";
        vm.again = "";
        vm.userType = "";
        vm.username = "";
        initNewCar();
    }
    ;

    function selectUserType(type) {
        vm.userType = type;
        if (vm.userType === "driver")
            vm.username = "";
        else
            initNewCar();
    }

    function isActive(type) {
        return type === vm.userType;
    }
    ;

    function checkCar() {
        return  CarService.findCarByEvc(vm.newCar.evidenceNumber).then(function (match) {
            if (match && match.data && match.data.data.length === 1)
                return true;
            else
                return false;
        });
    }
    ;

    function checkUsername() {
        return AuthService.findUserByUsername(vm.username).then(function (match) {
            if (match && match.data && match.data.data.length === 1)
                return true;
            else
                return false;
        });
    }
    ;

    function addCar() {
        CarService.create(vm.newCar).then(function () {
            onLogin({result: "Vy a vaše vozidlo ste boli úspešne zaregistrovaní."});
        }, function (err) {
            handleError(2, err);
        });
    }
    ;

    function addUser() {
        vm.parameters = {
            "userType": vm.userType,
            "username": vm.username
        };
        AuthService.signUp('firstName', 'lastName', vm.email, vm.password, vm.again, vm.parameters).then(function (response) {
            if (vm.userType === "driver") {
                vm.newCar.user = response.userId;
                addCar();
            } else
                onLogin({result: "Boli ste úspešne zaregistrovaný."});
        }, function (reason) {
            handleError(0, reason);
        });
    }
    ;

    function signUp() {
        if (vm.userType === "driver")
            checkCar().then(function (isExist) {
                if (isExist)
                    handleError(1);
                else
                    addUser();
            });
        else
            checkUsername().then(function (isExist) {
                if (isExist)
                    handleError(4);
                else
                    addUser();
            });
    }
    ;


    function handleError(code, error) {
        var errorPopup;
        var message;
        var buttons = [];
        var cssClass;
        var cancelButton = "button-calm";
        var okButtton = "button-assertive";

        if (code === 1) {
            message = "Zadané evidenčné číslo je už zaregistrované v carfriend.";
            cssClass = "popup-vertical-buttons";
            buttons.push({text: 'Zadať znova', type: okButtton}, {text: 'Zadať neskôr', type: cancelButton, onTap: function (e) {
                    vm.userType = "user";
                    addUser();
                }});
        }
        if (code === 0) {
            if (error.data && error.data.error_description)
                message = error.data.error_description === 'Membership failure:InvalidPassword' ? "Zadajte heslo o minimálnej dĺžke 6 znakov." : "Užívateľ s týmtom emailom je už zaregistrovaný v carfriend";
            else
                message = error.data === 'The password is is not confirmed' ? "Zadané heslá sa nezhodujú." : "Nastala neznáma chyba pri registrácii: " + error.data;
            buttons.push({text: 'Skúsiť znova', type: okButtton});
        }
        if (code === 2) {
            message = "Nastala neznáma chyba pri registrácii vášho vozidla: " + error.data;
            buttons.push({text: 'Skúsiť znova', type: okButtton});
        }
        if (code === 4) {
            message = "Užívateľ s touto prezývkou už existuje.";
            buttons.push({text: 'Skúsiť znova', type: okButtton});
        }

        errorPopup = $ionicPopup.show({
            title: 'Chyba!',
            template: message,
            cssClass: cssClass,
            buttons: buttons
        });
    }
    ;

    function onLogin(result) {
        $state.go('login', result);
    }
    ;

    $scope.$watch('vm.newCar.evidenceNumber', function (val) {
        vm.newCar.evidenceNumber = $filter('uppercase')(val);
    });

    function initNewCar() {
        vm.newCar = {evidenceNumber: '', color: '', user: ''};
    }
    ;

    function checkInputs() {
        if (vm.email && vm.password && vm.again && vm.userType) {
            if (vm.userType === 'driver') {
                if (vm.newCar.evidenceNumber && vm.newCar.color)
                    return true;
                else
                    return false;
            } else if (vm.username)
                return true;
            else
                return false;
        } else
            return false;
    }
    ;

}
;