/*
    SOURCE OF TRUTH THAT CONTROLS THE WHOLE WORKFLOW FOR THE APP
*/
const ActivityService = function ($window, $rootScope, $state, api, $q) {

    let script = null;
    let currentIndex = 0; //index in the script
    let currentActivityId = 0; //id of the current activity
    let completed = []; //id(s) of activities completed for all logged in users
    let activitiesComplete = false;
    let activities = [];

    function gotoNextActivity() {

        //console.log("entered gotonextActivity()-----------------------------");

        //api.getActivity(currentActivityId).then(function (response) {
        api.getActivities().then(function (response) {

            activities = response.data;

            if (activities[currentIndex].status == "stopped") {

                //console.log("GoToNextActivity: Entered the If statement");
                alert("The admin has stopped the activities. Please wait for instructions.");

            } else {
                //console.log("GoToNextActivity: Entered the Else statement");
                api.completeActivity(currentActivityId).then(function (response) {

                    api.getProgress().then(function (response) {

                        completed = response.data;

                        updateProgressVariables(); //will update currentIndex with the new activity index id

                        if (activitiesComplete) {
                            $state.go('done', {}, { reload: true });
                        } else if (activities[currentIndex].status != "disabled") {
                            gotoCurrentActivity();
                        } else {
                            gotoNextActivity();
                        }

                    });

                });
            }

        });

    }
    function goPrevActivity() {

        if (currentActivityId > 1) {

            api.deleteActivityProgress(currentActivityId - 1).then(function () {

                api.getProgress().then(function (response) {

                    completed = response.data;
                    updateProgressVariables();
                    if (activitiesComplete) {
                        $state.go('done', {}, { reload: true });
                    } else {

                        api.getActivities().then(function (response) {
                            activities = response.data;

                            if (activities[currentIndex].status == "disabled") {
                                goPrevActivity();

                            } else if ($state.current.name == 'activity') {
                                gotoCurrentActivity();
                            }
                        });
                    }
                });
            });
        }
    }

    //updates local variables for tracking activity progress
    //a script should already be loaded with api.getActivityScript();
    function updateProgressVariables() {

        let breakLoop = false;

        for (var i = 0; i < script.length; i++) {

            var a = script[i];
            if (!completed.includes(a.id)) {
                currentIndex = i;
                breakLoop = true;
                break;
            }
        }

        if (breakLoop) {
            currentActivityId = script[currentIndex].id;
            activitiesComplete = false;
        } else {
            currentIndex = 0;
            currentActivityId = 0;
            activitiesComplete = true;
        }
    }

    function gotoCurrentActivity() {
        $state.go('activity', {}, { reload: true });
    }

    this.getScript = function () {
        return api.getActivityScript().then(function (response) {
            script = response.data;
            debugger;
            return response;
        });
    };

    //returns specified activity data
    this.getActivity = function (id) {
        return api.getActivityScript().then(function (response) {
            var result = null;

            angular.forEach(script, function (item) {
                if (item.id == id)
                    result = item;
            });
            return result;
        });

    };

    //returns the current Activity from the ActivitiesScript
    this.getCurrentActivity = function () {
        //console.log("---------------------------getCurrentActivity called-------------------------------")

        return api.getActivityScript().then(function (response) {
            script = response.data;

            return api.getProgress().then(function (response) {

                completed = response.data;
                updateProgressVariables();

                //console.log(script[currentIndex]);
                return script[currentIndex];

            });
        });
    }

    //submits the userStory for all users logged in 
    this.submitStory = function (userStory) {

        return api.submitStory(userStory).then(function (responses) {
            var success = true;;
            responses.forEach(function (response) {
                if (response.data == false) {
                    success = false;
                    return success;
                }
            })
            return success;
        });
    }

    this.gotoNextActivity = function () {

        //console.log("entered gotonextActivity()-----------------------------");

        //api.getActivity(currentActivityId).then(function (response) {
        api.getActivities().then(function (response) {

            activities = response.data;

            if (activities[currentIndex].status == "stopped") {

                //console.log("GoToNextActivity: Entered the If statement");
                alert("The admin has stopped the activities. Please wait for instructions.");

            } else {
                //console.log("GoToNextActivity: Entered the Else statement");
                api.completeActivity(currentActivityId).then(function (response) {

                    api.getProgress().then(function (response) {

                        completed = response.data;

                        updateProgressVariables(); //will update currentIndex with the new activity index id

                        if (activitiesComplete) {
                            $state.go('done', {}, { reload: true });
                        } else if (activities[currentIndex].status != "disabled") {
                            gotoCurrentActivity();
                        } else {
                            gotoNextActivity();
                        }

                    });

                });
            }

        });

    }

    this.goPrevActivity = function () {

        if (currentActivityId > 1) {

            api.deleteActivityProgress(currentActivityId - 1).then(function () {

                api.getProgress().then(function (response) {

                    completed = response.data;
                    updateProgressVariables();
                    if (activitiesComplete) {
                        $state.go('done', {}, { reload: true });
                    } else {

                        api.getActivities().then(function (response) {
                            activities = response.data;

                            if (activities[currentIndex].status == "disabled") {
                                goPrevActivity();

                            } else if ($state.current.name == 'activity') {
                                gotoCurrentActivity();
                            }
                        });
                    }
                });
            });
        }
    }

    this.getCurrentActivityIndex = function () {
        return currentIndex;
    }

    this.getActivityCount = function () {

        if (script != null) {
            return script.length;
        }
    }

    this.completeCurrentActivity = function () {
        api.completeActivity(currentActivityId).then(function () {
        });
    }

    //this is called when user logs in or logs out
    $rootScope.$on('auth-changed', function () {
        if (api.isLoggedIn()) {
            init();
        }
    });

    function init() {
        //console.log("---------------------------init function called-------------------------------")
        api.getActivityScript().then(function (response) {
            script = response.data;

            api.getProgress().then(function (response) {

                completed = response.data;
                updateProgressVariables();

                //printState();

                if (activitiesComplete) {
                    $state.go('done', {}, { reload: true });
                } else {
                    if ($state.current.name == 'activity') {
                        $state.go('activity', {}, { reload: true });
                    }
                }
            });
        });

    }

    this.activitiesComplete = function () {
        return activitiesComplete;
    }

    printState = function () {
        console.log("currentIndex");
        console.log(currentIndex);
        console.log("currentActivityID");
        console.log(currentActivityId);
        console.log("completed");
        console.log(completed);
        console.log("activitiesComplete");
        console.log(activitiesComplete);
        console.log("script");
        console.log(script);
    }

    //dev cheats: call next(); in console to move to next activity - doesnt save progress
    //init();
    window.next = this.gotoNextActivity;
};