(function () {
    var moduleName = 'taskDetailApp';

    angular.module(moduleName)
        .controller("taskDetailCtrl", ['$scope', '$http', 'Task', 'breadcrumb.service', taskDetailController]);

    function taskDetailController($scope, $http, Task, breadcrumbService) {
        /**
         * Data setup
         */

        $scope.project_id = project_id;

        /**
         * Task methods
         */
        $scope.project_id = project_id;
        $scope.project_name = project_name;
        $scope.perms        = project_perms;
        $scope.task         = new Task();
        $scope.task.loadFromArray(task);

        $scope.task.due_date_formatted = task.due_date_formatted;
        $scope.task.created_by         = task.created_by;
        $scope.task.followed           = task.follow !== null;

        $scope.tabs =
            {
                discussionCount: 0,
                fileCount: 0
            };

        var breadcrumb = [];

        if ($scope.project_id > 0) {
            breadcrumb.push(
                {
                    'url': '/projects',
                    'name': lmsg('projects.breadcrumb.projects')
                },
                {
                    'url': '/projects/' + $scope.project_id,
                    'name': $scope.project_name
                },
                {
                    'url': '/projects/' + $scope.project_id + '#/tasksTab',
                    'name': lmsg('projects.breadcrumb.tasks')
                }
            );
        } else {
            breadcrumb.push(
                {
                    'url': '/projects/tasks',
                    'name': lmsg('projects.breadcrumb.tasks')
                });
        }

        breadcrumb.push(
            {
                'url': '',
                'name': $scope.task.title
            });

        breadcrumbService.setCrumbs(breadcrumb);

        $scope.setFollowButtonTitle = function () {
            if ($scope.task.followed)
                $scope.task.follow_tooltip = lmsg('projects.project.unfollow');
            else
                $scope.task.follow_tooltip = lmsg('projects.project.follow');
        };
        $scope.setFollowButtonTitle();

        $scope.determineVisibleTab = function () {
            var possibleTabs = [];
            if ($scope.task.perms.can_view_discussion)
                possibleTabs.push('discussion');
            possibleTabs.push('files');
            possibleTabs.push('history');

            // Get first visible tab to use as default
            var tab = possibleTabs[0];

            // Find if one was supplied in the URL
            var regex   = /#\/([\w]+)Tab/;
            var matches = regex.exec(window.location.hash);

            var byUrl = '';
            if ((matches !== null) &&
                (matches.length > 1))
                byUrl = matches[1];

            if (possibleTabs.indexOf(byUrl) > -1)
                tab = byUrl;

            $scope.tab = tab;
        };

        $scope.determineVisibleTab();

        $scope.onTabClick = function (tabName) {
            window.location.hash = '/' + tabName;
        };

        $scope.taskDeleted = function (task) {
            var parent_url = '/projects/tasks';
            if ($scope.task.project_id != 0)
                parent_url = '/projects/' + $scope.task.project_id;
            window.location.href = parent_url + '?message=' + encodeURIComponent(lmsg('projects.task_deleted'));
        };

        $scope.taskUpdated = function (task) {
            $scope.task.loadFromArray(task);
            $scope.updateHistoryLog();
        };

        $scope.clickComplete = function (event) {
            //zero-length timeout to ensure we run immediately after the digest finishes
            //this guarantees that we have the updated value of $scope.task.is_complete
            setTimeout(function() {
                if ($scope.task.is_complete) {
                    $scope.task.setComplete(function () {
                    }, function () {
                    });
                } else {
                    $scope.task.setIncomplete(function () {
                    }, function () {
                    });
                }

                $scope.updateHistoryLog();
            }, 0)
        };

        $scope.setStatus = function (event) {
            $scope.task.setStatus();
        };

        $scope.toggleFollow = function () {
            var url = '/api/projects/task/' + $scope.task.id + '/follow';

            if ($scope.task.followed) {
                $http.delete(url)
                    .then(function (result) {
                        angular.element('#follow-button').tooltip('hide');
                        $scope.task.followed = result.data.follow;
                        $scope.setFollowButtonTitle();
                    });
            } else {
                $http.put(url)
                    .then(function (result) {
                        angular.element('#follow-button').tooltip('hide');
                        $scope.task.followed = result.data.follow;
                        $scope.setFollowButtonTitle();
                    });
                $scope.updateHistoryLog();
            }
        };

        $scope.updateHistoryLog = function () {
            $scope.$root.$broadcast('updateHistoryLog', null);
        };

        $scope.isTaskCompletable = function (task) {
            var result = false;
            var assignees_to = [];

            task.assignees.map(function(assignee) {
                assignees_to.push(assignee.id)
            });

            if (assignees_to.includes($scope.perms.user_id) &&
                ($scope.perms.can_update_own_task_status)) {
                result = true;
            }

            if (assignees_to.includes($scope.perms.user_id) &&
                ($scope.perms.can_edit_own_task)) {
                result = true;
            }

            if ($scope.perms.can_edit_any_task) {
                result = true;
            }

            return result;
        };

        $scope.isTaskEditable = function (task) {
            var result = false;
            var assignees_to = [];

            task.assignees.map(function(assignee) {
                assignees_to.push(assignee.id)
            });

            if (assignees_to.includes($scope.perms.user_id) &&
                ($scope.perms.can_edit_own_task)) {
                result = true;
            }

            if ($scope.perms.can_edit_any_task) {
                result = true;
            }

            return result;
        };

        $scope.$on('setDiscussionTabCount', function (event, args) {
            $scope.tabs.discussionCount = args;
        });

        $scope.$on('setFilesTabCount', function (event, args) {
            // TODO in phase 2 - Keep as 0 for now to not display anything
            //$scope.tabs.fileCount = args;
        });
    }
}());
