(function (angular) {
    angular
        .module('todoList.list')
        .controller('listModifyController', listController);

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

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

        vm.activate = activate;
        vm.list = null;
        vm.listId = 0;
        vm.submit = submit;

        activate();
        $rootScope.setTitle('List | ' +
                            vm.listId
                                ? 'Edit list#' + vm.listId
                                : 'Add new list');

        ////////////////

        function activate() {
            vm.listId = $routeParams.listId;
            if (angular.isDefined(vm.listId)) {
                vm.list = ListService.get({listId: vm.listId});
            } else {
                vm.list = {listId: 0, name: null};
            }
        }

        function submit(form) {
            $scope.setDirty(form);
            //form.$error
            if (form.$valid) {
                var list = {};
                list.name = vm.list.name;
                if (vm.list.listId) {
                    list.listId = vm.list.listId;

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

    }
})(angular);