(function () {
    'use strict';

    angular
        .module('contestacaoApp')
        .directive('fileUpload', fileUpload);

    function fileUpload($parse) {

        let directive = {
            link: link,
            restrict: 'A',
            scope: false
        };

        return directive;

        function link(scope, element, attrs) {
            let model = $parse(attrs.fileUpload);
            let modelSetter = model.assign;
            let isMultiple = attrs.multiple;

            element.bind("change", function () {
                scope.$apply(function () {
                    let attachment = null;
                    if (isMultiple) {
                        attachment = element[0].files;
                    } else {
                        attachment = element[0].files[0];
                    }
                    modelSetter(scope, attachment);
                });
            });
        }
    }

})();
