(function (angular) {
    angular
        .module('todoList.task')
        .controller('taskController', taskController);

    taskController.$inject = ['$rootScope', 'TaskService', '$routeParams'];

    /* @ngInject */
    function taskController($rootScope, taskService, $routeParams) {
        /* jshint validthis: true */
        var vm = this;

        vm.activate = activate;
        vm.delete = remove;
        vm.deleteCanceled = deleteCanceled;
        vm.deleteConfirmed = deleteConfirmed;
        vm.tasks = [];
        vm.itemToDelete = null;
        vm.itemToDeleteIndex = 0;
        vm.setStatus = setStatus;

        activate();
        ////////////////

        function activate() {
            $rootScope.setTitle('List#' + vm.listId + ' | Tasks');
            vm.listId = $routeParams.listId;
            vm.tasks = taskService.query();
        }

        function setStatus(task, status) {
            task.status = status;
            taskService.update({taskId: task.taskId}, task).$promise.then(
                function () { },
                function () {
                    $rootScope.messages.add('danger', 'Danger, ',
                                            'There was on error updating the tasks status.');
                    task.status =
                        status == 1
                            ? 2
                            : 1;
                });
        }

        function remove(item, index) {
            vm.itemToDelete = item;
            vm.itemToDeleteIndex = index;
            $('#delete-confirm-modal').modal({}).on('hidden.bs.modal', function (e) {
                deleteCanceled();
            })
        }

        function deleteCanceled() {
            vm.itemToDelete = null;
            vm.itemToDeleteIndex = 0;
        }

        function deleteConfirmed() {
            if (vm.itemToDelete) {
                taskService.delete({taskId: vm.itemToDelete.taskId}).$promise.then(function () {
                    $rootScope.messages.add('success', 'Success, ', 'The task has been deleted successfully');
                    vm.tasks.splice(vm.itemToDeleteIndex, 1);
                    $('#delete-confirm-modal').modal('hide')
                });
            }
        }
    }
})(angular);