(function()
{
    var template = require('../../html/project/tasks.directive.html');
	var moduleName = 'claromentis.project';

	angular.module(moduleName)
        .directive('clangProjectTasks', projectTask);

    function projectTask() {
        controller.$inject = ['$rootScope', '$localStorage', 'claProjectDetailsService'];

        return {
            restrict: 'E',
            templateUrl: template,
            scope: {
                tasks: '<',
                lists: '<',
                statuses: '<',
                perms: '<',
                archiveDate: '<'
            },
            controllerAs: 'tasks',
            bindToController: true,
            controller: controller,
            link: link
        };

        function controller($rootScope, $localStorage, detailsService)
        {
            var ctrl = this;

            // These two are kept in local storage to remember user preferences
            ctrl.viewMode = 'list';
            ctrl.groupByList = true

            ctrl.showCompleted = false;
            ctrl.isMobile = true;
            ctrl.formattedTasks = {
                lists: []
            };

            ctrl.hideText = lmsg('projects.details.hide');
            ctrl.notGroupedText = lmsg('projects.details.not_grouped');

            this.$onInit = function() {
                ctrl.localStorageViewPrefsKey = 'projectTasks-ViewPrefs-' + ctrl.perms.user_id;

                if ($localStorage[ctrl.localStorageViewPrefsKey] !== undefined)
                {
                    if ($localStorage[ctrl.localStorageViewPrefsKey].viewMode !== undefined)
                        ctrl.viewMode = $localStorage[ctrl.localStorageViewPrefsKey].viewMode;
                    if ($localStorage[ctrl.localStorageViewPrefsKey].groupByList !== undefined)
                        ctrl.groupByList = $localStorage[ctrl.localStorageViewPrefsKey].groupByList;
                } else
                {
                    $localStorage[ctrl.localStorageViewPrefsKey] = {
                        viewMode: ctrl.viewMode,
                        groupByList: ctrl.groupByList
                    };
                }

                ctrl.buildTasks(ctrl.viewMode);
            };

            $rootScope.$on('task_list_data.updated', function($event, data) {
                var viewMode = ctrl.viewMode;

                if ((data !== undefined) && (data.view !== undefined))
                    viewMode = data.view;

                $localStorage[ctrl.localStorageViewPrefsKey].viewMode = viewMode;

                ctrl.buildTasks(viewMode);

                $rootScope.$broadcast('updateHistoryLog', null);
            });

            ctrl.onToggleVisibility = function() {
                $localStorage[ctrl.localStorageViewPrefsKey].groupByList = ctrl.groupByList;

                ctrl.buildTasks(ctrl.viewMode);
            }

            ctrl.buildTasks = function(viewMode) {

                var taskCount = 0;
                ctrl.formattedTasks.lists.length = 0;

                if (viewMode === 'board')
                {
                    if (ctrl.groupByList)
                    {
                        for (var listIndex = 0; listIndex < ctrl.lists.length; listIndex++)
                        {
                            var statuses = [];

                            for (var statusIndex = 0; statusIndex < ctrl.statuses.length; statusIndex++)
                            {
                                var tasks = [];

                                for (var taskIndex = 0; taskIndex < ctrl.tasks.length; taskIndex++)
                                {
                                    if ((ctrl.tasks[taskIndex].section_id == ctrl.lists[listIndex].id) &&
                                        (ctrl.tasks[taskIndex].status_id == ctrl.statuses[statusIndex].id) &&
                                        ((ctrl.tasks[taskIndex].date_completed > ctrl.archiveDate) || (ctrl.tasks[taskIndex].date_completed === null)))
                                    {
                                        tasks.push(ctrl.tasks[taskIndex]);
                                    }
                                }

                                // Sort by board_order
                                tasks.sort(function(a, b){
                                    if (a.orders.board < b.orders.board)
                                        return -1;
                                    if (a.orders.board > b.orders.board)
                                        return 1;
                                    return 0;
                                });

                                statuses.push({
                                    status: ctrl.statuses[statusIndex],
                                    tasks: tasks
                                });

                                taskCount += tasks.length;
                            }

                            ctrl.formattedTasks.lists.push({
                                list: ctrl.lists[listIndex],
                                listId: parseInt(ctrl.lists[listIndex].id),
                                listName: ctrl.lists[listIndex].title,
                                statuses: statuses
                            });
                        }
                    } else
                    {
                        var statuses = [];

                        for (var statusIndex = 0; statusIndex < ctrl.statuses.length; statusIndex++)
                        {
                            var tasks = [];

                            for (var taskIndex = 0; taskIndex < ctrl.tasks.length; taskIndex++)
                            {
                                if ((ctrl.tasks[taskIndex].status_id === ctrl.statuses[statusIndex].id) &&
                                    ((ctrl.tasks[taskIndex].date_completed > ctrl.archiveDate) || (ctrl.tasks[taskIndex].date_completed === null)))
                                {
                                    var task = ctrl.tasks[taskIndex];

                                    var listColour = '#FFFFFF';
                                    for (var listIndex = 0; listIndex < ctrl.lists.length; listIndex++)
                                    {
                                        if (ctrl.lists[listIndex].id == task.section_id)
                                            listColour = ctrl.lists[listIndex].colour;
                                    }
                                    task.listColour = listColour;

                                    tasks.push(task);
                                }
                            }

                            // Sort by board_order
                            tasks.sort(function(a, b){
                                if (a.orders.board_no_list < b.orders.board_no_list)
                                    return -1;
                                if (a.orders.board_no_list > b.orders.board_no_list)
                                    return 1;
                                return 0;
                            });

                            statuses.push({
                                status: ctrl.statuses[statusIndex],
                                tasks: tasks
                            });

                            taskCount += tasks.length;
                        }

                        ctrl.formattedTasks.lists.push({
                            listColour: listColour,
                            statuses: statuses
                        });
                    }
                } else
                {
                    for (var listIndex = 0; listIndex < ctrl.lists.length; listIndex++)
                    {
                        var tasks = [];

                        for (var taskIndex = 0; taskIndex < ctrl.tasks.length; taskIndex++)
                        {
                            if ((ctrl.tasks[taskIndex].section_id == ctrl.lists[listIndex].id) &&
                                ((ctrl.showCompleted) ||
                                (ctrl.tasks[taskIndex].status_id != -2)))
                            {
                                tasks.push(ctrl.tasks[taskIndex]);
                            }
                        }

                        // Sort by display_order
                        tasks.sort(function(a, b){
                            if (a.orders.list < b.orders.list)
                                return -1;
                            if (a.orders.list > b.orders.list)
                                return 1;
                            return 0;
                        });

                        ctrl.formattedTasks.lists.push({
                            listName: ctrl.lists[listIndex].title,
                            listId: parseInt(ctrl.lists[listIndex].id),
                            list: ctrl.lists[listIndex],
                            tasks: tasks
                        });

                        taskCount += tasks.length;
                    }
                }

                // Hide any visible tooltips before the screen is redrawn
                angular.element('a[rel="tooltip"]').tooltip('hide');

                // Update the sidebar with current visible task count
                detailsService.setTaskCount(taskCount, ctrl.tasks.length);
            }
        }

        function link(scope, element, attr, ctrl) {

            var mobileWidth = 767;

            ctrl.isMobile = document.body.clientWidth <= mobileWidth;

            angular.element(window).on('resize', function(event) {
                ctrl.isMobile = document.body.clientWidth <= mobileWidth;
                scope.$digest();
            });
        }
    }
}());
