(function(paw, utils){
    function PawAttachmentUploadErrorMessage(attachmentErrorsRaw) {
        if(utils.value.isSet(attachmentErrorsRaw) && attachmentErrorsRaw.length > 0){
            var attErrorsRaw = utils.value.strReplace(attachmentErrorsRaw, '\r', '<br />');
            attErrorsRaw = utils.value.strReplace(attErrorsRaw, '\n', '<br />');
            attErrorsRaw = utils.value.strReplace(attErrorsRaw, '\t', '<br />');
            this.attachmentErrors = JSON.parse(attErrorsRaw);
        }
    }

    PawAttachmentUploadErrorMessage.prototype.markupDef = function(bind){
        var markup = [];
        utils.iterable.iterate(bind.message.messages, function(msg){
            markup.push('<div style="padding: 16px;"><p>' + msg + '</p></div>');
        });
        return markup;
    };

    PawAttachmentUploadErrorMessage.prototype.init = function(){
        var self = this;
        if(!utils.value.isSet(this.attachmentErrors) || this.attachmentErrors.length === 0){
            return;
        }
        var normalizedMessages = this.normalizeMessages(this.attachmentErrors);
        var popup = new paw.com.Popup('attachment-upload-popup', {
            title: normalizedMessages.title,
            type: 'error',
            maximizable: false,
            markupDef: function(bind){
                return self.markupDef(bind);
            },
            bind: {
                message: normalizedMessages
            }
        });
        popup.show();
    };
    
    PawAttachmentUploadErrorMessage.prototype.normalizeMessages = function(attachmentErrors){
        var messages = [];
        var actions = [];
        var titles = [];

        utils.iterable.iterate(attachmentErrors, function(attErr){
            if(messages.indexOf(attErr.Error) > -1){
                return;
            }
            messages.push(attErr.Error);
            if(titles.indexOf(attErr.Title) === -1){
                titles.push(attErr.Title);
            }
            utils.iterable.iterate(attErr.Buttons, function(btn){
                if(actions.indexOf(btn) > -1){
                    return;
                }
                actions.push(btn);
            });
        });
        return {
            messages: messages,
            actions: actions,
            title: titles.length >= 1? titles[0] : ""
        };
    };

    paw.com.UploadAttachmentErrorMessage = PawAttachmentUploadErrorMessage;
})(paw, paw.utils);