'use strict';

oml.ui.annotation = function(annotation, $iframe) {
    var $quoteText = Ox.Element()
        .addClass('OxSelectable OMLQuote')
        .html(Ox.encodeHTMLEntities(annotation.text).replace(/\n/g, '<br/>'))
        .on({
            click: function(event) {
                that.select()
                $iframe.postMessage('selectAnnotation', {
                    id: annotation.id
                })
            }
        });
    var $quoteBackground = Ox.Element().addClass('OMLQuoteBackground');
    var $quote = Ox.Element()
        .addClass('OMLQuoteBox')
        .append(
            $quoteBackground
        ).append(
            $quoteText
        );
    var notes = annotation.notes.length ? annotation.notes.map(function(note) {
        note.editable = !note.user
        return note
    }) : [];
    var $notes = Ox.ArrayEditable({
        editing: true,
        items: notes,
        placeholder: 'Add note',
        type: 'textarea'
    }).css({
        minHeight: '12px'
    }).bindEvent({
        doubleclick: addNote,
        submit: function(data) {
            var note = Ox.getObjectById(annotation.notes, data.id)
            if (note) {
                note.value = data.value
                note.modified = (new Date).toISOString()
            } else {
                annotation.notes.push({
                    created: data.created || (new Date).toISOString(),
                    modified: (new Date).toISOString(),
                    id: data.id,
                    user: '',
                    value: data.value
                })
            }
            that.triggerEvent('change')
        }
    });
    var that = Ox.Element().attr({
        id: 'a-' + annotation.id
    }).addClass(
        'OxSelectable OMLAnnotation'
    ).css({
        borderBottom: '1px solid rgb(208, 208, 208)',
    }).bindEvent({
        key_delete: function() {
            that.triggerEvent('delete', {
                id: annotation.id
            })
        }
    }).append($quote).append($notes);


    function addNote() {
        if (!$notes.options('items').length) {
            that.select()
            $notes.addItem(0, {
                id: 'A',
                value: '',
                editable: true
            }).options({
                selected: 'A'
            }).editItem()
        }
    }


    that.annotate = function() {
        if (oml.user.ui.showAnnotations) {
            addNote()
        }
    }
    that.deselect = function() {
        that.removeClass('selected')
        that.loseFocus()
    }
    that.select = function () {
        $iframe.postMessage('selectAnnotation', {
            id: annotation.id
        })
        let selected = document.querySelector('.OMLAnnotation.selected')
        selected && selected.classList.remove('selected')
        that.addClass('selected')
        that.gainFocus()
        that[0].scrollIntoViewIfNeeded()
    }
    return that;
};