(function()
{
    var moduleName = 'taskListApp';
    var template = require('../../../html/directives/tasklist/tasklist_filters.directive.html');

    angular.module(moduleName)
        .directive('clangTasklistFilters', taskListFilters);

    taskListFilters.$inject = ['tasklistService'];
    function taskListFilters(service)
    {
        return {
            restrict: 'E',
            templateUrl: template,
            scope: {},
            controllerAs: 'ctrl',
            bindToController: true,
            controller: controller
        };

        function controller($scope, $timeout)
        {
            var ctrl = this;

            ctrl.task_filters = [];
            ctrl.status_filters = [];

            this.$onInit = function() {
                ctrl.initData();

                service.onChange(function()
                {
                    ctrl.initData();
                });
            };

            ctrl.initData = function()
            {
                ctrl.currentTaskFilter = service.currentTaskFilter;
                ctrl.task_filters.length = 0;
                for (var i = 0; i < service.task_filters.length; i++)
                {
                    ctrl.task_filters.push(service.task_filters[i]);
                }

                ctrl.currentStatusFilter = service.currentStatusFilter;
                ctrl.status_filters.length = 0;
                for (var i = 0; i < service.status_filters.length; i++)
                {
                    ctrl.status_filters.push(service.status_filters[i]);
                }

                // Force a directive redraw after this one has finished (ng doesn't know that visible data has changed to do it automatically)
                $timeout(function() {
                    $scope.$digest();
                }, 0);
            }

            // Listen for the back or forward buttons being pressed and adjust the page content according to the URL
            window.addEventListener('popstate', function()
            {
                // Store current state to check if anything changed later
                var oldTaskFilter = ctrl.currentTaskFilter;
                var oldStatusFilter = ctrl.currentStatusFilter;
                var oldPage = ctrl.currentPage;
                var oldUserFilter = ctrl.userFilter;
                var oldSearchTerms = ctrl.searchTerms;

                // Reset all filters to default values
                ctrl.currentTaskFilter = 'my_tasks';
                ctrl.currentStatusFilter = 'open';
                ctrl.userFilter = null;
                ctrl.currentPage = 1;
                ctrl.searchTerms = '';

                // Set filters according to URL
                var params = History.getState().hash.split('?')[1];
                if (typeof params !== 'undefined')
                {
                    var parts = params.split('&');

                    for (var i = 0; i < parts.length; i++)
                    {
                        var vars = parts[i].split('=');
                        switch (vars[0])
                        {
                            case 'task_filter':
                            {
                                ctrl.currentTaskFilter = vars[1];
                                break;
                            }
                            case 'status_filter':
                            {
                                ctrl.currentStatusFilter = vars[1];
                                break;
                            }
                            case 'page':
                            {
                                ctrl.currentPage = vars[1];
                                break;
                            }
                            case 'user_filter':
                            {
                                ctrl.userFilter = vars[1];
                                break;
                            }
                            case 'search':
                            {
                                ctrl.searchTerms = vars[1];
                                break;
                            }
                        }
                    }
                }

                // Only reload if something has actually changed
                if ((oldTaskFilter != ctrl.currentTaskFilter) ||
                    (oldStatusFilter != ctrl.currentStatusFilter) ||
                    (oldPage != ctrl.currentPage) ||
                    (oldUserFilter != ctrl.userFilter) ||
                    (oldSearchTerms != ctrl.searchTerms))
                {
                    ctrl.getResultsPage(true);
                }
            });

            // If a filter is clicked
            ctrl.setTaskFilter = function($event, type, count) {
                $event.preventDefault();
                if (count === '')
                    return;
                ctrl.currentTaskFilter = type;
                if (ctrl.currentTaskFilter === 'my_tasks')
                    ctrl.listViewName = lmsg('projects.tasks.custom_order');
                else
                    ctrl.listViewName = lmsg('projects.tasks.list_view');
                ctrl.currentPage = 1;
                service.currentTaskFilter = ctrl.currentTaskFilter;
                service.getResultsPage();
            };

            ctrl.setStatusFilter = function($event, type, count) {
                $event.preventDefault();
                if (count === '')
                    return;

                // Make sure completed tasks don't see the 'by due date' view
                if ((ctrl.view_mode === 'due_date') &&
                    (type !== 'open'))
                {
                    ctrl.view_mode = 'list_view';
                }

                ctrl.currentStatusFilter = type;
                ctrl.currentPage = 1;
                service.currentStatusFilter = ctrl.currentStatusFilter;
                service.getResultsPage();
            };
        }
    }
}());
