(function (paw, utils) {
    function NoteEditorComponent($elt, settings, localization, content) {
        var self = this;
        this.$elt = $elt;
        this.settings = paw.lang.append({
            onSave: null,
            onCancel: null,
            encode: 'none',
            autoFocus: true
        }, settings || {});
        this.localization = localization;
        this.content = content;

        this.editor = null;
        this.contentInput = null;

        this.actions = {
            save: {
                id: 'save',
                $elt: null,
                onSelected: function(){
                    if(utils.value.isFunction(self.settings.onSave)){
                        self.settings.onSave(self.encodeContent(DOMPurify.sanitize(self.editor.contentData.content)));
                    }
                }
            },
            cancel: {
                id: 'cancel',
                $elt: null,
                onSelected: function(){
                    if(utils.value.isFunction(self.settings.onCancel)){
                        self.settings.onCancel();
                    }
                }
            }
        };   
    }

    NoteEditorComponent.prototype.init = function(){
        var self = this;
        this.initEditor();

        // register actions events
        utils.iterable.iterate(this.actions, function(action){
            action.$elt = self.$elt.find('[note-editor-action="' + action.id + '"]');
            action.$elt.on('click', action.onSelected);
        });
    };

    NoteEditorComponent.prototype.destroy = function(){
        this.destroyEditor();
    };

    NoteEditorComponent.prototype.destroyEditor = function(){
        this.editor.contentField.unbind();
    };

    NoteEditorComponent.prototype.initEditor = function(){
        this.editor = {
            contentField: null,
            contentData: {
                content: this.decodeContent(this.content)
            }
        };
        this.editor.contentField = new paw.com.Input(this.$elt.find('textarea[data-note-editor-field="content"]'), 'content', this.editor.contentData);

        if (this.settings.autoFocus) {
            this.editor.contentField.focus();
        }
    };

    NoteEditorComponent.prototype.encodeContent = function(content){
        switch(this.settings.encode){
            case 'base64':
                return paw.utils.value.b64EncodeUnicode(content);
            case 'none':
            default:
                return content;
        }
    };

    NoteEditorComponent.prototype.decodeContent = function(content){
        switch(this.settings.encode){
            case 'base64':
                return paw.utils.value.b64DecodeUnicode(content);
            case 'none':
            default:
                return content;
        }
    };

    paw.com.noteEditor.NoteEditorComponent = NoteEditorComponent;
})(paw, paw.utils);