(function () {
    'use strict';
    angular.module('ti_common').directive('ticDragDropFileUpload', dragDrop);
    function dragDrop() {
        var directive = {
            templateUrl: 'ti_common/cloud/drag_drop_file_upload.html',
            restrict: 'E',
            controller: DragDropController,
            controllerAs: 'vm',
            scope: {
                uploading: '='
            },
            bindToController: true
        };
        return directive;
    }
    DragDropController.$inject = ['$q', '$scope', 'ticFileStorage', 'ticAlerts', 'Upload'];
    function DragDropController($q, $scope, ticFileStorage, ticAlerts, Upload) {
        var vm = this;
        var FILE_SIZE_LIMIT = 52428800;
        vm.autoSelectUploads = true;
        $scope.$watch('vm.domFiles', function () {
            vm.upload(vm.domFiles);
        });
        vm.upload = function (domFiles) {
            var uploads = [];
            if (domFiles && domFiles.length) {
                // create a temp fd;
                _.each(domFiles, function (domFile) {
                    if (!domFile.$error && domFile.size < FILE_SIZE_LIMIT) {
                        var file = ticFileStorage.upload(domFile);
                        uploads.push(file);
                    }
                    else if (domFile.size >= FILE_SIZE_LIMIT) {
                        // file size limit error
                        ticAlerts.showError(domFile.name + " exceeded the file size limit.");
                    }
                });
                if (vm.uploading) {
                    // let them know uploading complete
                    vm.uploading(uploads, !vm.autoSelectUploads);
                    vm.done = $q.resolve(); // move on.. let who ever is handling he uploading.. show progress
                }
                else {
                    vm.done = $q.all(uploads);
                }
            }
        };
    }
})();
