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

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

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

        vm.activate = activate;
        vm.task = null;
        vm.taskId = 0;
        vm.submit = submit;


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

        function activate() {
            vm.taskId = $routeParams.taskId;
            vm.listId = $routeParams.listId;

            $rootScope.setTitle('List#' + vm.listId + ' | Tasks | ' +
                                vm.taskId
                                    ? 'Edit task#' + vm.taskId
                                    : 'Add new task');

            if (angular.isDefined(vm.taskId)) {
                vm.task = taskService.get({taskId: vm.taskId});
            } else {
                vm.task = {taskId: 0, title: null, description: null, status: 1};
                vm.task.list = listService.get({listId: vm.listId});
            }
        }



        function submit(form) {
            $scope.setDirty(form);
            //form.$error
            if (form.$valid) {
                var task = {};
                task.title = vm.task.title;
                task.description = vm.task.description;
                task.status = 1;
                task.list = vm.task.list;

                if (vm.task.taskId) {
                    task.taskId = vm.task.taskId;

                    taskService.update({taskId: task.taskId}, task).$promise.then(function () {
                        $rootScope.messages.add('success', 'Success, ', 'task modified successfully');
                        $location.path('/list/' + vm.listId + '/task');
                    });
                } else {
                    taskService.save(task).$promise.then(function () {
                        $rootScope.messages.add('success', 'Success, ', 'New task created successfully');
                        $location.path('/list/' + vm.listId + '/task');
                    });
                }
            }
        }

    }
})(angular);