(function () {
    'use strict';
    // generic UI For listing files
    angular.module('ti_common').directive('ticFiles', ticFiles);
    ticFiles.$inject = ['$timeout'];
    function ticFiles($timeout) {
        var directive = {
            restrict: 'E',
            templateUrl: 'ti_common/files.html',
            scope: {
                files: '=',
                filesSelected: '=',
                noFilesMessage: '=',
                showUploadDialog: '=',
                getDefaultFiles: '=',
                getAllFiles: '=',
                showRecent: '=',
                filter: '=',
                filterType: '='
            },
            controller: FilesController,
            controllerAs: 'vm',
            bindToController: true,
            link: link
        };
        function link(scope, element) {
            scope.$watch('vm.files.length', function () {
                var tbody = element.find('tbody');
                $timeout(function () {
                    tbody.scrollTop = tbody.scrollHeight;
                }, 0, false);
            });
        }
        return directive;
    }
    FilesController.$inject = ['ticAlerts'];
    function FilesController(ticAlerts) {
        var vm = this;
        vm.selectedFilter = 'default';
        vm.showAllFiles = function (isShow) {
            if (vm.selectedFilter === 'all') {
                vm.getAllFiles();
            }
            else {
                vm.getDefaultFiles();
            }
        };
        vm.uploading = function (uploads, keepOpen) {
            if (keepOpen) {
                var newFiles = uploads.concat(vm.files);
                vm.files = newFiles;
            }
            else {
                vm.filesSelected(uploads);
            }
        };
        vm.fileSelected = function (file) {
            return vm.filesSelected([file]);
        };
        vm.deleteFile = function (file) {
            return ticAlerts.showConfirm('Delete File', 'Permanently delete ' + file.name + '?')
                .then(function () {
                return file.delete();
            }).then(function () {
                _.remove(vm.files, function (currFile) {
                    return file === currFile;
                });
            });
        };
    }
})();
