(function() {

    angular
        .module('simbioinfoControllers')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$q', '$rootScope', '$scope', '$parse', '$http', '$location', '$angularCacheFactory',
        '$templateCache', '$sce', 'appCache', 'authService', 'CommonService'];

    function LoginCtrl($q, $rootScope, $scope, $parse, $http, $location, $angularCacheFactory, $templateCache, $sce,
                       appCache, authService, CommonService) {
        var vm = this;

        vm.doLogin = doLogin;

        // Initialize the services into the scope.
        $scope.as = authService;
        $scope.cf = $angularCacheFactory;
        // Initialize the user variables used in the controller from localStorage.
        // $scope.userCache is shorthand for: $angularCacheFactory.get('userCache')
        $scope.userCache = $scope.cf.get('userCache');
        $scope.rememberMe = $scope.userCache.get('rememberMe');
        $rootScope.userName = $scope.userCache.get('userName');
        // Initialize the auth variables used in the controller from sessionStorage.
        // $scope.authCache is shorthand for: $angularCacheFactory.get('authCache')
        $scope.authCache = $scope.cf.get('authCache');
        $scope.authSet = $scope.authCache.get('authSet');

        $rootScope.versionNumberStr = 'swp_v2400202207222105';
        //console.log("Login Version String: " + $rootScope.versionNumberStr);

        $scope.serverDown = false;
        // If the user chose to be remembered read in their user name.
        if ($scope.rememberMe === true) {
            $rootScope.userName = $scope.userCache.get('userName');
        }
        // Watch for a change in rememberMe from the view and store the value.
        $scope.$watch('rememberMe', function () {
            $scope.userCache.put('rememberMe', $scope.rememberMe);
            if ($scope.rememberMe === true) {
                $scope.userCache.put('userName', $rootScope.userName);
            } else {
                $scope.userCache.put('userName', "");
            }
            $rootScope.userName = $scope.userCache.get('userName');
        });

        $rootScope.$on('$routeChangeStart', function(event, next, current) {
            if (typeof(current) !== 'undefined'){
                $templateCache.remove(current.templateUrl);
            }
        });

        // Country detection for download modal and header logo.
        $scope.detectedCountry = "";
        $scope.detectCountry = function () {
            if (!$scope.detectedCountry) {
                $scope.releasePromise = authService.getSystemRelease($scope.authSet)
                    .then(function (response) {
                        // Boolean conditionals are established for UI interaction.
                        $scope.authCache.put('isAuthenticated', response.isAuthenticated);
                        $scope.authCache.put('isError', response.isError);
                        $scope.releaseInfo = response.data;
                        //console.log("Release info: ",$scope.releaseInfo);
                    })
                    .then(function () {
                        $scope.detectedCountry = $scope.releaseInfo.environment.substring(0, 6); // Ex. 'prodca' for Canada (currently covers 'prodca' and 'prodca2')
                        // Obviously, this isn't the best way to do this. Having the REST call announce the server's country would be optimal.
                        if ($scope.detectedCountry === 'prodca') { // Maybe change to JavaScript case statement if more countries are added.
                            $scope.detectedCountryHuman = 'Canada'; // Only Canada requires specification at the moment.
                        } else if ($scope.detectedCountry === 'prodmx') { // This does nothing right now. Use this as a template if another country is added.
                            // You should also use detectedCountryHuman to conditionally change the last two images in the modal to something specific to a Mexico install.
                            $scope.detectedCountryHuman = 'Mexico'; // This is the 'human friendly' name used in the modal text.
                        } else { // Everything except Canada at this point is everything else.
                            $scope.detectedCountry = 'main'; // If the detected country is 'main' then the modal won't show.
                            $scope.detectedCountryHuman = 'Other'; // Includes US, international, and well... everything else.
                        }
                    });
            }
        };
        $scope.detectCountry();

        $scope.hideModal = function (id) {
            if (id === "altLogin") {
                //Resetting admin
                $scope.adminLogin = false;
            }
            $('#'+id).modal('hide');
        };
        $scope.showModal = function (id) {
            $('#'+id).modal('show');
        };

        $scope.goToRegister = function(){
            window.location.replace("../student/register.html");
        };
        $scope.goToSupport = function(){
            window.location.replace("https://simutext.zendesk.com/hc/en-us");
        };

        $rootScope.currPortal = $location.absUrl().split('/')[3];
        $rootScope.currServer = $location.absUrl().split('/')[2];

        //console.log ("Current Portal: " + $rootScope.currPortal);
        if ($rootScope.currPortal) {
            $scope.promise = authService.getSystemMessages($rootScope.currPortal)
                .then(function (response) {
                    $rootScope.systemMessages = response.data;
                })
        }

        $scope.school = [];
        $scope.school.selected = [];
        $scope.educator = [];
        $scope.educator.selected = [];
        $scope.$watch('school.selected', function () {
            if ($scope.school.selected.id) {
                if ($scope.school.selected.id) {
                    $scope.promise = authService.getSchoolEducators($scope.authSet, $scope.school.selected.id)
                        .then(function (response) {
                            $scope.educatorArray = response.data;
                        })
                }
            }
        });

        // CGBusy Defaults
        $scope.minDuration = 1000;
        $scope.message = 'Loading...';

        // On load we'll assume that it's not an alt login
        $scope.authCache.put('alt_login', false);
        $scope.adminLogin = false;

        $rootScope.schoolArray = [];
        $scope.showForgotPass = false;
        $scope.isAuthenticated = false;
        $scope.isLoginError = false;
        $scope.studentLogin = false;
        // Takes username and password from the page and passes it to the authService to get the authSet.
        function doLogin(userName, password) {
            $scope.isLoginError = false;
            $scope.studentLogin = false;
            $scope.schoolPromise = authService.setCredentials(userName, password)
                .then(function (response) {
                    // Boolean conditionals are established for UI interaction.
                    $scope.authCache.put('isAuthenticated', response.isAuthenticated);
                    $scope.authCache.put('isLoginError', response.isError);
                    $scope.isLoginError = response.isError;
                    if (response.httpStatus !== 422 && response.httpStatus !== 404) {
                        // Store the rest of the Auth info in LocalStorage since it will be heavily reused.
                        $scope.authCache.put('token_type', response.data.token_type);
                        $scope.authCache.put('access_token', response.data.access_token);
                        $scope.authCache.put('expires_in', response.data.expires_in);
                        $scope.authCache.put('refresh_token', response.data.refresh_token);
                        $scope.authCache.put('authSet', response.data.token_type + ' ' + response.data.access_token);
                        $scope.userCache.put('userName', userName);
                        // Check for E0, Use alt login if necessary
                        var pre_access_token = response.data.access_token;
                        pre_access_token = pre_access_token.substr(0,2);
                        if (pre_access_token === "E0") {
                            // Administrative login detected!
                            $scope.adminLogin = true;
                            $scope.getSchoolList();
                            $scope.showModal('altLogin');
                        } else if ((pre_access_token === "10") && $rootScope.currPortal==='instructor') {
                            // Student login detected
                            $scope.studentLogin = true;
                            $scope.isLoginError = true;
                            $scope.adminLogin = false;
                            $scope.authCache.put('alt_login', false);
                            return $q.reject(response);
                        } else {
                            // Just to be doubly sure...
                            $scope.adminLogin = false;
                            $scope.authCache.put('alt_login', false);
                        }
                    }
                    // Check the HTTP status from the response and set an error flag.
                    if (response.httpStatus === 422 || response.httpStatus === 404 || response.httpStatus === 503) {
                        $scope.isLoginError = true;
                        if (response.httpStatus === 503) {
                            $scope.serverDown = true;
                        }
                    }
                    delete $scope.password;
                }, function (response) {
                    $scope.isLoginError = true;
                    return $q.reject(response);
                }).then(function () {
                    if ($scope.isLoginError == false && !$scope.adminLogin) {
                        // Jump to the main page.
                        if ($rootScope.currPortal === 'instructor') {
                            window.location.replace( "../instructor/main.html#/home" );
                        } else if ($rootScope.currPortal === 'student') {
                            window.location.replace( "../student/main.html#/home" );
                        }

                    }
                })
        };

        $scope.getSchoolList = function() {
            $scope.authSet = $scope.authCache.get('authSet');
            authService.getSchoolList($scope.authSet)
                .then(function (response) {
                    $rootScope.schoolArray = response.data;
                });
        };

        $scope.doAltLogin = function (educatorId) {
            $scope.isLoginError = false;
            authService.mimeEducator($scope.authSet, educatorId)
                .then(function (response) {
                    // Boolean conditionals are established for UI interaction.
                    $scope.authCache.put('isAuthenticated', response.isAuthenticated);
                    $scope.authCache.put('isLoginError', response.isError);
                    $scope.isLoginError = response.isError;
                    if (response.httpStatus !== 422 && response.httpStatus !== 404) {
                        // Store the rest of the Auth info in LocalStorage since it will be heavily reused.
                        $scope.userCache.put('userName', response.data.educatorOutModel.name);
                        $scope.authCache.put('alt_login', true);
                    }
                    // Check the HTTP status from the response and set an error flag.
                    if (response.httpStatus === 422 || response.httpStatus === 404) {
                        $scope.isLoginError = true;
                    }
                    delete $scope.password;
                }, function (response) {
                    $scope.isLoginError = true;
                    return $q.reject(response);
                }).then(function () {
                if ($scope.isLoginError == false) {
                    // Jump to the main page.
                    window.location.replace( "../instructor/main.html#/home" );
                }
            })
        };

        $scope.doReset = function (resetName) {
            $scope.isAuthenticated = false;
            $scope.isLoginError = false;
            authService.resetUserPassword(resetName)
                .then(function (response) {
                    // Boolean conditionals are established for UI interaction.
                    $scope.authCache.put('isAuthenticated', response.isAuthenticated);
                    $scope.authCache.put('isLoginError', response.isError);
                    $scope.isLoginError = response.isError;
                    if (response.httpStatus !== 422 || response.httpStatus !== 404) {

                    }
                    // Check the HTTP status from the response and set an error flag.
                    if (response.httpStatus === 422 || response.httpStatus === 404) {
                        $scope.isLoginError = true;
                    }
                }, function (response) {
                    $scope.isLoginError = true;
                    return $q.reject(response);
                }).then(function () {
                $scope.isLoginError = false;
                $scope.showForgotPass = false;
                if ($scope.isLoginError == false) {
                    // Jump to the main page.
                    //window.location.replace( "main.html#/home" );
                }
            })
        };

        function getVersionInfo() {
            $scope.releasePromise = authService.getSystemRelease($scope.authSet)
                .then(function (response) {
                    // Boolean conditionals are established for UI interaction.
                    $scope.authCache.put('isAuthenticated', response.isAuthenticated);
                    $scope.authCache.put('isError', response.isError);
                    $scope.releaseInfo = response.data;
                    console.log("Release info: ",$scope.releaseInfo);
                })
        }
        getVersionInfo();
    }

})();