'use strict';

angular.module('app')
    .directive('annotationEditor', function($rootScope, $log, $filter, HtmlKeywordsUnderliner) {
        return {
   	        template: require('./annotation-editor.html'),
            restrict: 'E',
            scope: {
                text: '=',
                selectedText: '=',
                annotations: '=',
                origin: '='
            },
            link: function(scope, el) {

                function render() {
                    $log.debug('AnnotationEditor - running render() method');
                    var annotations;

                    if (!scope.annotations) {
                        return;
                    }
                    annotations = scope.annotations.filter(function(ann) {
                        return ann.origin === scope.origin;
                    });

                    scope.text = $filter('replaceHtmlEntities')(scope.text);
                    scope.text = HtmlKeywordsUnderliner.removeAnyUnderlyingByString(scope.text, true);
                    scope.text = HtmlKeywordsUnderliner.underlineAnnotationsByTextAndAnnotations(scope.text, annotations, true);
                }

                var selectedValue = '';

                el.ready(function() {
                    $rootScope.$emit('annotationEditorIsRendered');
                });

                render();

                scope.$watch('annotations', function(newV) {
                    if (!newV) {
                        return;
                    }
                    render();
                });
                $rootScope.$on('ANNOTATION_SAVED', function() {
                    render();
                });
                $rootScope.$on('REVIEW_SAVED', function() {
                    render();
                });


                var getSelectionFromWindow = function() {
                    var selectedText = '';
                    if (typeof window.getSelection !== undefined) {
                        var sel = window.getSelection();
                        if (sel.rangeCount) {
                            var container = document.createElement('div');
                            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                                container.appendChild(sel.getRangeAt(i).cloneContents());
                            }
                            selectedText = container.innerHTML;
                        }
                    } else if (typeof document.selection !== undefined) {
                        if (document.selection.type === 'Text') {
                            selectedText = document.selection.createRange().htmlText;
                        }
                    }
                    
                    selectedText = $filter('replaceAngularTags')(selectedText);
                    

                    return selectedText;
                };

                scope.calculateAnnotationBySelectionAndOriginalText = function(selectedText, text) {
                    // $log.info('selectedText, text', selectedText, text);
                    var cleanText,
                        cleanSelectedText;
                    var textHtmlEntitiesReplacerFilter;
                    textHtmlEntitiesReplacerFilter = $filter('textHtmlEntitiesReplacer');

                    cleanText = HtmlKeywordsUnderliner.removeAnyUnderlyingByString(text);
                    cleanText = textHtmlEntitiesReplacerFilter(cleanText);
                    cleanSelectedText = HtmlKeywordsUnderliner.removeAnyUnderlyingByString(selectedText);
                    cleanSelectedText = HtmlKeywordsUnderliner.removeAnyAngularAddedTagByString(cleanSelectedText);
                    cleanSelectedText = textHtmlEntitiesReplacerFilter(cleanSelectedText);

                    var annotation = {
                        text: cleanSelectedText,
                        start: cleanText.indexOf(cleanSelectedText),
                        offset: cleanSelectedText.length,
                        origin: scope.origin
                    };
                    // $log.info('annotation, cleanSelectedText, cleanText', annotation, cleanSelectedText, cleanText, cleanText.indexOf(cleanSelectedText));
                    scope.currentOrigin = scope.origin;
                    return annotation;
                };

                var emitSelectionEvent = function(emitOutput) {
                    if (emitOutput.text && emitOutput.text !== '') {
                        scope.selectedText = emitOutput.text;
                        scope.$emit('selectedText', emitOutput);
                    }
                };

                scope.getSelectionHtml = function() {
                    var selection = getSelectionFromWindow();
                    var emitOutput = scope.calculateAnnotationBySelectionAndOriginalText(selection, scope.text);
                    emitSelectionEvent(emitOutput);
                };


                scope.removeSelection = function() {
                    selectedValue = '';
                    scope.$emit('selectedText', '');
                };
            }
        };
    });