var EventDispatcher = require('../../event/EventDispatcher').EventDispatcher;

var RbmqMessage = function(params) {
    EventDispatcher.call(this);

    this._data = {};

    if (params && typeof params == 'object' && params.constructor == Object) {
        var methodName, key, value;
        for (key in RbmqMessage.Attributes) {

            if (params.hasOwnProperty(key)) {
                value = params[key];
            } else {
                value = RbmqMessage.Attributes[key];
            }

            methodName = key.charAt(0).toUpperCase() + key.substr(1);

            if (typeof this['set' + methodName] == 'function') {
                this['set' + methodName](value);
            }
        }
    }
};

RbmqMessage.Attributes = {
    'routingKey': undefined,
    'body': '',
    'headers': {},
    'mandatory': false,
    'immediate': false,
    'contentEncoding': undefined,
    'contentType': undefined,
    'deliveryMode': undefined,
    'appId': undefined,
    'messageId': undefined
};

RbmqMessage.prototype = Object.create(EventDispatcher.prototype);

Object.keys(RbmqMessage.Attributes).forEach(function(key) {
    var methodName = key.charAt(0).toUpperCase() + key.substr(1);

    RbmqMessage.prototype['set' + methodName] = function(value) {
        this._data[key] = value;
        return this;
    };

    RbmqMessage.prototype['get' + methodName] = function() {
        return this._data[key];
    };
});

RbmqMessage.prototype.hasHeader = function(name) {
    return this._data.headers.hasOwnProperty(name);
};

RbmqMessage.prototype.removeHeader = function(name) {
    if (this.hasHeader(name)) {
        delete this._data.headers[name];
    }
};

RbmqMessage.prototype.getHeader = function(name, defaultValue) {
    if (!this.hasHeader(name)) {
        return defaultValue;
    }

    return this._data.headers[name];
};

RbmqMessage.prototype.getArguments = function() {
    var args = JSON.parse(JSON.stringify(this._data));

    if (args.body) {
        delete args.body;
    }

    if (args.routingKey) {
        delete args.routingKey;
    }

    for (var key in Object.keys(args)) {
        if (args[key] === undefined) {
            delete args[key];
        }
    }

    return args;
};

RbmqMessage.Options = {};
/* Delivery mode non-persistant */
RbmqMessage.Options.DMODE_NON_PERSISTENT = 1;
/* Delivery mode persistant */
RbmqMessage.Options.DMODE_PERSISTENT = 2;

exports.RbmqMessage = RbmqMessage;
