'use strict';

oml.ui.annotation = function(annotation, $iframe) {
    var $arrayEditable = Ox.ArrayEditable({
        editing: true,
        items: (annotation.comments || []).map(function(comment) {
            comment.editable = true
            return comment
        }),
        type: 'textarea'
    }).css({
        minHeight: '16px'
    }).bindEvent({
        submit: function(data) {
            var comment = Ox.getObjectById(annotation.comments, data.id)
            if (comment) {
                comment.value = data.value
                comment.modified = (new Date).toISOString()
            } else {
                annotation.comments.push({
                    created: data.created || (new Date).toISOString(),
                    modified: (new Date).toISOString(),
                    id: data.id,
                    value: data.value
                })
            }
            that.triggerEvent('change')
        }
    });
    var that = Ox.Element().attr({
        id: 'a-' + annotation.id
    }).addClass(
        'OxSelectable'
    ).css({
        borderBottom: '1px solid rgb(208, 208, 208)',
    }).append(
        Ox.Element().addClass('OxSelectable').css({
            backgroundColor: 'white',
            color: 'black',
            fontFamily: 'Georgia, Palatino, DejaVu Serif, Book Antiqua, Palatino Linotype, Times New Roman, serif',
            fontSize: '14px',
            lineHeight: '21px',
            padding: '8px'
        }).html(Ox.encodeHTMLEntities(annotation.text).replace(/\n/g, '<br/>')).on({
            click: function(event) {
                $iframe.postMessage('selectAnnotation', {
                    id: annotation.id
                })
            }
        })
    ).append($arrayEditable);
    that.annotate = function() {
        var item = {
            id: 'note', value: '', editable: true
        }
        $arrayEditable.addItem(0, item)
            .options({selected: item.id})
            .editItem();
    }
    return that;
};