const AdminComponent = {
    templateUrl: "/app/admin/admin.component.html",
    controller: function ($state, $activity, api, $scope, $interval) {

        let $ctrl = this;
        $ctrl.activities = [];
        $ctrl.users = [];
        $ctrl.newUser = {};
        $ctrl.activeUsers = [];
        $ctrl.stoppedActivities = [];
        $ctrl.disabledActivities = [];

        getActivities = function () {
            api.getActivities().then(function (response) {
                $ctrl.activities = response.data;
                //console.log($ctrl.activities);
                $ctrl.activities.forEach(function (activity) {
                    let id = activity.id;
                    let status = activity.status;
                    if (status == "enabled") {
                        $ctrl.stoppedActivities[id] = false;
                        $ctrl.disabledActivities[id] = false;
                    } else if (status == "disabled") {
                        $ctrl.disabledActivities[id] = true;
                    } else if (status == "stopped") {
                        $ctrl.stoppedActivities[id] = true;
                    }
                });
            });
        }

        getUsersInfo = function () {
            api.getUsers().then(function (response) {
                $ctrl.users = response.data;
                api.getActivityStatus().then(function (res) {
                    var activities_list = res.data;
                    $ctrl.users.forEach(user => {
                        var user_activities = activities_list.filter((activity) => {
                            return activity.userId == user.id;
                        });
                        var completed_activity = user_activities.filter((act) => {
                            return act.state == "DONE";
                        })
                        user["activity_status"] = (completed_activity ? completed_activity.length : 0) + "/" + $ctrl.activities.length;
                        user["widthContainer"] = (completed_activity.length / $ctrl.activities.length * 100).toString() + "%";

                        /** 
                         Cannnot see that is doing something 
                        if (user.isActive == 1) {
                            var new_user = {};
                            console.log("$$$$$", completed_activity.length);
                            new_user['id'] = user.id;
                            new_user['host_name'] = $ctrl.hostname;
                            // if for a particualar user id , activity id 1 is there is activity list or not 
                            for (var x = 1; x <= completed_activity.length; x++) {

                                new_user['activity' + x] = true;

                            }
                            console.log("&&&&&&&", new_user);

                            $ctrl.activeUsers.push(new_user);

                        }
                        */
                    });
                })
            });
        }

        refresh = function () {
            if (api.isAdmin()) {
                getUsersInfo();
            }
        }

        $ctrl.$onInit = function () {
            if (api.isAdmin()) {
                getActivities();
                getUsersInfo();
                $interval(refresh, 10000);
            } else {
                $state.go('login');
            }
        }

        $ctrl.submitUser = function () {
            $ctrl.newUserForm.$submitted = true;

            if ($ctrl.newUserForm.$valid) {
                api.postUser($ctrl.newUser).then(function (response) {
                    $ctrl.users.push(response.data);
                    $ctrl.newUser = {};
                    $ctrl.newUserForm.$submitted = false;
                }, function (response) {
                    alert("Error creating user. Please check server logs. Status code: " + response.status);
                });
            }
        }

        //SP3
        $ctrl.importUsers = function () {
            var users_data = {};
            var new_users = [];

            if ($scope.fileContent) {
                users_data = $scope.fileContent.split(/\r\n|\n/);

                users_data.forEach(user => {
                    if (user && user.trim() != "") {
                        var data_arr = user.split(",");
                        if (data_arr != null && data_arr.length > 1) {
                            var user = {};
                            user['name'] = data_arr[0];
                            user['hash'] = data_arr[1];

                            //for (var i = 0; i < 10; i++) {
                                new_users.push(user);
                            //
                            //}

                        }

                    }

                })

                new_users.forEach(user => {

                    api.postUser(user).then(function (response) {


                        $ctrl.users.push(response.data);
                    }, function (response) {
                        alert("Error importing user" + newUser + ". Please check server logs. Status code: " + response.status);
                    });

                })

            }

        };

        //SP3
        $ctrl.downloadUserStories = function () {
            api.getUserStory().then(function (response) {
                var user_story_list = response.data;
                alasql('SELECT userID,text,submitTime INTO CSV("UserStories.csv", {headers:true, separator:","}) FROM ?', [user_story_list]);
            });
        }

        $ctrl.viewUserStory = function (userNumber) {
            api.getUserStory().then(function (response) {
                var user_story_list = response.data;
                for (var i = 0; i < user_story_list.length; i++) {
                    if (user_story_list[i]["userID"] === userNumber) {
                        alert(user_story_list[i]["text"]);
                    }
                }

                // console.log(user_story_list[userNumber - 1]);
            });
        }

        $ctrl.updateActivities = function () {
            var statuses = []
            angular.forEach($ctrl.activities, function (value, index) {
                if ($ctrl.stoppedActivities[index + 1] == true) {
                    statuses[index + 1] = "stopped";
                } else if ($ctrl.disabledActivities[index + 1] == true) {
                    statuses[index + 1] = "disabled";
                } else {
                    statuses[index + 1] = "enabled";
                }

            });

            console.log(statuses);
            console.log($ctrl.stoppedActivities);

            //console.log($ctrl.stoppedActivities);
            api.setActivitiesStatus(statuses).then(function () {
                getActivities();
            });
        }

        $ctrl.resetActivities = function () {
            var statuses = []
            angular.forEach($ctrl.activities, function (value, index) {
                statuses[index + 1] = "enabled";
            });
            api.setActivitiesStatus(statuses).then(function () {
                getActivities();
            });
        }

        $ctrl.kickUser = function (userId) {
            //console.log("kicking userId " + userId);
            api.kickUser(userId, api.getAuthToken()).then(function (response) {
                console.log(response.data);
                if (response.data == "false") {
                    alert("Unable to kick out user");
                }
            })
        }
    }
};