coreFramework.directive('cfVariations', function () {
    return {
        restrict: 'A',
        controller: ['$scope', '$attrs', 'StaticService', function($scope, $attrs, StaticService) {
            if (!$attrs.cfVariations) {
                $scope.variations = StaticService.editorVariations;
                $scope.cfVariations = {};
                $scope.$watch('variations', function() {
                    if ($scope.variations.length) {
                        angular.forEach($scope.variations, function(item) {
                            $scope.cfVariations[item.code] = item.name;
                        });
                        $attrs.$set('cfVariations', JSON.stringify($scope.cfVariations).replace(/"/g, '\''));
                    }
                }, true);
            }
        }]
    };
});

coreFramework.directive('cfDrop', function ($parse, AssignmentMediator, AssignmentService, StaticService, Restangular) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            function setEditor(editor) {

                editor.assignImages = function() {
                    scope.$apply(function() {
                        AssignmentMediator.register(insertImageAtCursor, 'image');
                    });
                };
                editor.assignFiles = function() {
                    scope.$apply(function() {
                        AssignmentMediator.register(insertFileAtCursor, 'file');
                    });
                };
                editor.insertImageGallery = function() {
                    var div = new CKEDITOR.dom.element('div');
                        div.setAttribute('class', 'ContentGalleryPlaceholder');
                        div.setAttribute('contenteditable', 'false');
                        div.appendHtml('Image Gallery');
                    editor.insertElement(div);
                };

                //var defaultImageVariation = scope.defaultImageVariation || 'admin_small';
                // var defaultImageVariation = attrs.defaultImageVariation || 'admin_small';

                var imageObjects = {};

                function insertFileAtCursor(file) {
                    var klass = file.url.split('.').pop().toLowerCase() + ' fileDownload';
                    var a = new CKEDITOR.dom.element('a');
                        a.setAttribute('title', file.title);
                        a.setAttribute('href', file.url);
                        a.setAttribute('class', klass);
                        a.appendHtml(file.title);
                    var p = new CKEDITOR.dom.element('p');
                        p.append(a);
                    editor.insertElement(p);

                }

                function insertImageAtCursor(image) {

                    var defaultImageVariation = (function () {
                        var variations;
                        if (attrs.defaultImageVariation) {
                            variations = StaticService.editorVariations.filter(function (item) {
                                return item.code == attrs.defaultImageVariation;
                            });
                            if (variations.length) {
                                return variations[0].code;
                            }
                        }
                        if (StaticService.editorVariations.length) {
                            return StaticService.editorVariations[0].code;
                        }
                        return 'admin_small';
                    }());
                    
                    if (angular.isUndefined(imageObjects[image.id])) {
                        imageObjects[image.id] = image;
                    }

                    var imageURL;
                    var imageVariation;
                    angular.forEach(image.variations, function(variation) {
                        if (variation.code == defaultImageVariation) {
                            imageVariation = variation;
                        }
                    });
                    if (imageVariation) {
                        // imageURL = variation.path;
                        imageURL = imageVariation.url.replace(/^(ftp|http|https):\/\/(.+)\//, '/');
                    }

                    var img = new CKEDITOR.dom.element('img');
                        img.setAttribute('src', imageURL);
                        img.data('id', image.id);
                        var imgCaption = attrs.defaultImageCaption && $parse(attrs.defaultImageCaption)(image);
                        if (imgCaption) {
                            img.data('caption', encodeURI(imgCaption));
                        }
                    var p = new CKEDITOR.dom.element('p');
                        p.append(img);
                    editor.insertElement(p);
                    /*
                    Restangular.oneUrl('image', '/api/images/' + image.id + '/').get({'select': 'Variations'}).then(function (response) {
                        img.setAttribute('src', response.data.originalElement.variations[angular.isDefined(scope.defaultImageVariation) ? scope.defaultImageVariation : 'admin_small'].url);
                    });
                    */
                }

                editor.on('contentDom', function(e) {

                    editor.on('focus', function(e) {

                        //AssignmentMediator.register(insertImageAtCursor, 'image');

                    });

                    editor.on('change', function(e) {

                        updateImageList();

                    });
                });

                function updateImageList() {

                    var images = getImageList();
                    var imageList = [];

                    angular.forEach(images, function(image) {
                        if (angular.isDefined(imageObjects[image])) {
                            imageList.push(imageObjects[image]);
                        }
                    });

                    AssignmentService.add('image', attrs.name, imageList);

                }

                function getImageList() {

                    var images = [];
                    $(editor.getData()).find('img[data-id]').each(function(i, el) {
                        var id = String($(this).data('id'));
                        if (images.indexOf(id) == -1) {
                            images.push(id);
                        }
                    });

                    return images;

                }

                function loadImages(final) {

                    var images = getImageList();
                    var params = angular.extend({'query': 'id:[' + images.toString() + ']'}, scope.$eval(attrs.apiParams || {'select': ['Variations.*']}));

                    if (images.length) {
                        Restangular.one(attrs.apiEndpoint || 'images').get(params).then(function (response) {
                            angular.forEach(response.data.originalElement, function(image) {
                                if (image && image.id) {
                                    imageObjects[image.id] = image;
                                }
                            });
                            updateImageList();
                        }, function (error) {

                        });
                    } else if (!final) {
                        var init = scope.$watch(function() { return editor.getData(); }, function(value) {
                            if (value) {
                                loadImages(true);
                                init();
                            }
                        });
                    }

                }

                if (!editor.loadImagesStarted) {
                    editor.loadImagesStarted = true;
                    loadImages();
                }

            }
            for (var i in CKEDITOR.instances) {
                setEditor(CKEDITOR.instances[i]);
            }
            CKEDITOR.on('instanceCreated', function(e) {
                setEditor(e.editor);
            });

        }
    };
});
