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

    angular.module(moduleName, ['claromentis.my_tasks', 'cla.core.lmsg', 'preloadModule'])
        .controller('myTasksCtrl', function($scope, $http, $timeout, preload) {
            var ctrl = this;

            ctrl.tasks = preload.myTasks;
            ctrl.showCompleted = preload.showCompleted;
            ctrl.groupByProject = preload.groupByProject;
            ctrl.projectList = preload.projectList;
            ctrl.showAll = false;
            ctrl.canShowAll = preload.canShowAll;
            ctrl.userId  = preload.userId;
            ctrl.ajax_params = preload.ajaxParams;
            ctrl.showSectionNames = preload.showSectionNames;
            ctrl.showAssignees = preload.showAssignees;
            ctrl.ajax_url = '/api/projects/widget/tasks';
            ctrl.isPagesComponent = preload.isPagesComponent;
            var initializing = true;

            $scope.$watch('ctrl.showAll', function(newVal, oldVal) {
                if (initializing) {
                    $timeout(function () {
                        initializing = false;
                    });

                    return;
                }

                var params = ctrl.ajax_params;
                params.only_mine = newVal?0:1;

                $http.get(ctrl.ajax_url, {
                    params: params
                }).then(function (response) {
                    var tasks    = response.data.tasks;
                    var projects = response.data.projects;

                    ctrl.tasks = [];
                    for (var i = 0; i < tasks.length; i++)
                        ctrl.tasks.push(tasks[i]);

                    ctrl.projectList = [];
                    for (i = 0; i < projects.length; i++)
                        ctrl.projectList.push(projects[i]);
                }, function () {
                    console.log("Rejected request");
                });
            });
        });
}());
