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

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

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

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

        activate();
        $rootScope.setTitle('Lists');

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

        function activate() {
            vm.lists = ListService.query();
        }

        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) {
                ListService.delete({listId: vm.itemToDelete.listId}).$promise.then(function () {
                    $rootScope.messages.add('success', 'Success, ', 'The list has been deleted successfully');
                    vm.lists.splice(vm.itemToDeleteIndex, 1);
                    $('#delete-confirm-modal').modal('hide')
                });
            }
        }
    }
})(angular);