coreFramework.directive('cwUpload', function () {
    return {
        restrict: 'E',
        scope: {
            data: '=ngModel',
            saveUrl: '@',
            saveField: '@',
            contentType: '@',
            saveRefresh: '@'
        },
        template: '<input type="file" kendo-upload k-async="opts" k-on-success="onSuccess(kendoEvent)" k-on-upload="onUpload(kendoEvent)" />',
        controller: ['$scope', function ($scope) {
            
            $scope.opts = {
                saveUrl: $scope.saveUrl,
                saveField: $scope.saveField,
                // removeUrl: '<%= url({"entity": "images"}, "api") %>',
                // removeField: 'images',
                // removeVerb: 'DELETE',
                autoUpload: true
            };

            $scope.onSuccess = function (response) {
                // var location = response.XMLHttpRequest.getResponseHeader('Location');
                // getImageInfo(location);
                
                // TODO: ovdje treba signalizirati dataSourceu od obližnjeg cwList da napravi fetch()
                $scope.saveRefresh();
            };

            $scope.onUpload = function (e) {
                var xhr = e.XMLHttpRequest;

                if (xhr) {
                    xhr.addEventListener('readystatechange', function (e) {
                        if (xhr.readyState == 1) {
                            // FIXME: get auth header
                            xhr.setRequestHeader('Authorization', 'Bearer abc123');
                        }
                    });
                }
            };

            // function getImageInfo(path) {
            //     Restangular.oneUrl('repository', path).get().then(function(response) {
            //         // console.log('image data', response.data.originalElement);
            //         $rootScope.$emit('article.HeaderImage', response.data.originalElement);
            //     });
            // }

        }],
        link: function (scope, element, attrs, ctrl) {}
    };
});
