var Request = require('../net/Request.js').Request;
var JsonRpcRequest = require('../jsonrpc/JsonRpcRequest').JsonRpcRequest;
var BinaryData = require('../data/BinaryData.js').BinaryData;

/**
 * @class OpalRequest
 * @extends Request
 * @requires Class
 * @requires Request
 *
 */
var OpalRequest = exports.OpalRequest= function (data) {
    Request.call(this);

    this._remoteMethod = null;        

    if (data) {
        if (!data.hasOwnProperty('url') || !data.hasOwnProperty('method')) {
            throw OpalRequest.Exception.INCOMPLETE_PARAMS;
        }

        if (data.url.substring(0, 8) == 'https://') {
            this.setPort(443);
            this.setHeader('host', data.url.replace('https://', '').replace('/', ''));
        } else {
            this.setPort(80);
            this.setHeader('host', data.url.replace('http://', '').replace('/', ''));
        }

        // tutaj mozna nadpisac np na inny gateway/router
        this.setConnectionHost(data.url);

        this.setRemoteMethod(data.method);
        this.setMethod(Request.POST);

        if (data.hasOwnProperty('application') && data.application) {
            this.setApplication(data.application);
        } else if (process.env['OPAL_IDENTITY']) {
            this.setApplication(process.env['OPAL_IDENTITY']);
        } else {
            this.setApplication('localhost.front.onetapi.pl');
        }

        var json = new JsonRpcRequest({
                'id': this.getRemoteMethod() + '-' + +new Date(),
                'method': this.getRemoteMethod()
            }),
            bData;
        
        if (data.params) {
            json.setParams(data.params);
        }
        bData = new BinaryData(json.toString(), BinaryData.Encoding.TEXT, BinaryData.CharacterEncoding.UTF8);

        this.setBody(bData);

        this.setHeader('content-type', 'application/json-rpc');
        this.setHeader('content-length', bData.length());
    }
};

OpalRequest.prototype = Object.create(Request.prototype);

/**
 * sets the application ident string
 * @param {String} app
 * @returns {OpalRequest}
 */
OpalRequest.prototype.setApplication = function (app) {
    this.setHeader('x-onet-app', app, true);

    return this;
};

/**
 * returns application ident string
 * @returns {OpalRequest}
 */
OpalRequest.prototype.getApplication = function () {
    return this.getHeader('x-onet-app');
};

/**
 * sets method of communicating with a service
 * @param {String} method
 * @returns {OpalRequest}
 */
OpalRequest.prototype.setRemoteMethod = function (method) {
    this._remoteMethod = method;

    return this;
};

/**
 * returns method of communicating with a service
 * 
 * @returns {OpalRequest}
 */
OpalRequest.prototype.getRemoteMethod = function () {
    return this._remoteMethod;
};

OpalRequest.Exception = {};
OpalRequest.Exception.INCOMPLETE_PARAMS = 'Incomplete params given';
