(function() {

    var app = angular.module('ngCkeditor');

    app.directive('drop', function (StaticService, AssignmentMediator, Restangular, $timeout) {

    return {
        restrict: 'A',
        transclude: false,
        replace: false,
        scope: {
            images: '=drop',
            defaultImageVariation: '@'
        },
        controller: ['$scope', function ($scope) {

            $scope.variations = StaticService.variations;

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

            //CKEDITOR.config.disableObjectResizing = true;
            /*
            scope.$watch('[variations]', function() {
                if (scope.variations.length && angular.isDefined(scope.variationMenu)) {
                    scope.variationMenu.startGroup('Varijacija slike');
                    for (var i = 0; i < scope.variations.length; i++){
                        scope.variationMenu.add(scope.variations[i].code, scope.variations[i].name, scope.variations[i].name);
                    }
                    scope.variationMenu.disable();
                }
            }, true);
            */

            CKEDITOR.plugins.add('image_variations', {

                requires: ['richcombo'],
                init : function(editor) {

                    var config = editor.config;
                        config.disableObjectResizing = true;

                    var lang = editor.lang.format;

                    var variationExp = /(\-)([^\-]*)(\.)/i; // -<variation>.

                    function buildList() {
                        for (var i = 0; i < scope.variations.length; i++){
                            this.add(scope.variations[i].code, scope.variations[i].name, scope.variations[i].name);
                        }
                        this.changeSelected();
                    }

                    function getSelectedImage(editor) {

                        var el = editor.getSelection().getSelectedElement();
                        if (el && el.is('img')) {
                            return el;
                        }
                        return null;

                    }

                    function getVariation(el) {

                        var src = el.getAttribute('src');
                        var r = variationExp.exec(src);
                        if (r) {
                            return r[2];
                        }
                        return null;

                    }

                    function setVariation(el, variation) {

                        var src = el.getAttribute('src');
                            src = src.replace(variationExp, '$1' + variation + '$3');
                        el.setAttribute('src', src);
                        return src;

                    }

                    editor.ui.addRichCombo('ImageVariations', {

                        label: 'Image variation',
                        title: 'Image variation',
                        voiceLabel: 'Image variation',
                        className : 'cke_image_variations',
                        multiSelect : false,

                        panel: {
                            css: [CKEDITOR.skin.getPath('editor')].concat(config.contentsCss)
                        },

                        init: function() {

                            this.startGroup('Image variation');

                            this.disable();

                            var rebuildList = CKEDITOR.tools.bind(buildList, this);

                            if (scope.variations.length) {
                                rebuildList();
                            } else {
                                scope.$watch('variations', function() {
                                    if (scope.variations.length) {
                                        rebuildList();
                                    }
                                });
                            }
                        },

                        onRender: function() {

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

                                this.changeSelected();

                            }, this);

                        },

                        changeSelected: function() {

                            if (!scope.variations.length) {
                                return;
                            }

                            var el = getSelectedImage(editor);
                            if (el) {
                                var variation = getVariation(el);
                                if (variation) {
                                    for (var i = 0; i < scope.variations.length; i++) {
                                        if (variation == scope.variations[i].code) {
                                            this.setValue(scope.variations[i].code, scope.variations[i].name);
                                            //this.setState(CKEDITOR.TRISTATE_OFF);
                                            this.enable();
                                            return;
                                        }
                                    }
                                }
                            }

                            this.setValue('', this.label);
                            //this.setState(CKEDITOR.TRISTATE_DISABLED);
                            this.disable();

                        },

                        onClick : function(variation) {

                            editor.focus();
                            var el = getSelectedImage(editor);
                            if (el) {

                                editor.fire( 'saveSnapshot' );
                                setVariation(el, variation);
                                editor.fire( 'saveSnapshot' );
                                this.changeSelected();

                            }

                        }
                    });
                }

            });

            CKEDITOR.on('instanceCreated', function(e) {

                var editor = e.editor;

                function insertImageAtCursor(image) {

                    var img = new CKEDITOR.dom.element('img');
                        img.setAttribute('src', image.variations.admin_small.url);
                        img.data('id', image.id);
                    editor.insertElement(img);

                    Restangular.oneUrl('image', '/api/images/' + image.id + '/').get().then(function (response) {
                        img.setAttribute('src', response.data.originalElement.variations[angular.isDefined(scope.defaultImageVariation) ? scope.defaultImageVariation : 'admin_small'].url);
                    });

                }

                function getImageList() {

                    var imageList = [];
                    $(editor.getData()).find('img[data-id]').each(function(i, el) {
                        imageList.push({
                            id: String($(this).data('id'))
                        });
                    });
                    /*
                    $timeout(function() {
                        scope.images = [2];
                    });
                    console.log(scope.images);
                    */
                    scope.images = imageList;

                }

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

                        AssignmentMediator.register(insertImageAtCursor, 'image');

                    });

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

                        getImageList();

                    });
                });

                getImageList();

            });


            return;

            console.log('f');
            scope.$watch('[variations]', function() {
                console.log('e');
                if (scope.variations.length) {
                    drop_init();
                }
            }, true);

            function drop_init() {
                console.log('d');


            }

            scope.add = function (item) {
                console.log(item);
            }


            var variations = scope.variations;
            var variationDefault = scope.defaultImageVariation;
            var variationExp = /(\-)([^\-]*)(\.)/i; // -<variation>.

            function getSelectedImage(editor) {

                var el = editor.getSelection().getSelectedElement();
                if (el && el.is('img')) {
                    return el;
                }
                return null;

            }

            function getVariation(el) {

                var src = el.getAttribute('src');
                var r = variationExp.exec(src);
                if (r) {
                    return r[2];
                }
                return null;

            }

            function setVariation(el, variation) {

                var src = el.getAttribute('src');
                    src = src.replace(variationExp, '$1' + variation + '$3');
                el.setAttribute('src', src);
                return src;

            }

            function validateVariation(el) {

                var variation = getVariation(el);
                for (var i = 0; i < variations.length; i++) {
                    if (variation == variations[i].id) {
                        return true;
                    }
                }
                return false;

            }

CKEDITOR.config.extraAllowedContent = 'img[data-id]';
CKEDITOR.config.disableObjectResizing = true;



            CKEDITOR.on('instanceCreated', function(e) {
                var editor = e.editor;

                editor.on('contentDom', function() {
                    editor.document.on('drop', function(e) {
                        //editor.insertText('');
                        //console.log(e);
                        //console.log(e.data.$.dataTransfer.getData("Text"));

                        editor.insertHtml('');
                        //console.log(editor.getData());
                        //e.data.preventDefault(true);
                    });
                    editor.on('beforeUndoImage', function(e) {

                        //console.log(e);
                        var data = $(editor.getData());
                        //console.log(new CKEDITOR.dom.element(editor.document.$.getElementsByTagName('img')[0]));
                        var update = false;
                        data.find('img[data-id]').each(function(i, el) {
                            if ($(this).parent().is('a')) {
                                $(this).unwrap();
                                update = true;
                            }
                            if ($(this).attr('ng-src')) {
                                $(this).attr('src', $(this).attr('ng-src'));
                                $(this).removeAttr('ng-src');
                                update = true;
                            }
                            if (variationDefault) {
                                if (!validateVariation(this)) {
                                    $(this).attr('src', setVariation(this, variationDefault));
                                    update = true;
                                }
                            }
                        });

                        if (update) {
                            editor.editable().setHtml($('<div />').html(data).html());

                        }

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

                        getImageList();

                    });
                    editor.on('focus', function(e) {
                        scope.insert.setInsertMethod(insertImageAtCursor);
                    });

                    function insertImageAtCursor(image) {

                        var img = new CKEDITOR.dom.element('img');
                            img.setAttribute('src', image.src);
                            img.data('id', image.id);
                        editor.insertElement(img);

                    }

                    function getImageList() {

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

                        scope.images = imageList;

                        //scope.$apply(function () {
                            //scope.items = imageList;
                        //});

                    }
                    getImageList();
                });
            });

CKEDITOR.plugins.add('image_variations', {

    requires: ['richcombo'],
    init : function(editor) {

        var config = editor.config;
        var lang = editor.lang.format;

        editor.ui.addRichCombo('ImageVariations', {

            label: 'Varijacija slike',
            title: 'Varijacija slike',
            voiceLabel: 'Varijacija slike',
            className : 'cke_image_variations',
            multiSelect : false,

            panel: {
                css: [CKEDITOR.skin.getPath('editor')].concat(config.contentsCss)
            },

            init: function() {

                this.startGroup('Varijacija slike');

                for (var i = 0; i < variations.length; i++){
                    this.add(variations[i].id, variations[i].label, variations[i].label);
                }

                this.disable();

            },

            onRender: function() {

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

                    this.changeSelected();

                }, this);

            },

            changeSelected: function() {

                var el = getSelectedImage(editor);
                if (el) {
                    var variation = getVariation(el);
                    if (variation) {
                        for (var i = 0; i < variations.length; i++) {
                            if (variation == variations[i].id) {
                                this.setValue(variations[i].id, variations[i].label);
                                //this.setState(CKEDITOR.TRISTATE_OFF);
                                this.enable();
                                return;
                            }
                        }
                    }
                }

                this.setValue('', this.label);
                //this.setState(CKEDITOR.TRISTATE_DISABLED);
                this.disable();

            },

            onClick : function(variation) {

                editor.focus();
                var el = getSelectedImage(editor);
                if (el) {

                    editor.fire( 'saveSnapshot' );
                    setVariation(el, variation);
                    editor.fire( 'saveSnapshot' );
                    this.changeSelected();

                }

            }
        });
    }
});
        }
    };
});

})();