const LoginComponent = {
    templateUrl: "/app/login/login.component.html",
    controller: function ($rootScope, $state, api) {
        let $ctrl = this;
        $ctrl.username = null;
        $ctrl.users = [{}];
        $ctrl.error = false;
        $ctrl.errorText = "";


        isAdminInUsers = function () {

            let isAdmin = false;
            angular.forEach($ctrl.users, function (value, key) {
                if (value.name == "admin") {
                    isAdmin = true;
                }
            });
            return isAdmin;
        }

        $ctrl.$onInit = function () {

            //SP4 Working      
            if (api.isLoggedIn()) {
                if(api.isAdmin()){
                    $state.go('admin');
                } else if (!api.isAdmin()){
                    $state.go('activity', {}, { reload: true });
                }            
            }         
        }

        $ctrl.deleteUser = function ($index) {
            $ctrl.users.splice($index, 1);
        }

        $ctrl.addUser = function () {
            if ($ctrl.users.length < 3)
                $ctrl.users.push('');
        }

        $ctrl.submit = function () {

            //console.log(isAdminInUsers());
            if (isAdminInUsers() && $ctrl.users.length > 1) {
                $ctrl.errorText = "The admin cannot log in with a student.";
                $ctrl.error = true;
                return;
            }

            api.logIn($ctrl.users).then(function (response) {

                let answer = response.data;

                if (answer.includes("is logged in machine")) {
                    $ctrl.errorText = answer;
                    $ctrl.error = true;
                } else if (answer == "false") {
                    $ctrl.errorText = "Invalid username or password for one of the users.";
                    $ctrl.error = true;
                } else {
                    if (api.isAdmin()) {
                        $state.go('admin');
                        //console.log("Go to Admin from ApiLogin");
                    } else {
                        $state.go('activity'); //added on SP4
                    }
                }
            })
        }

    }
};