var OpalResponse = require('./OpalResponse.js').OpalResponse;
var Event = require('../event/Event.js').Event;
var ErrorEvent = require('../event/ErrorEvent.js').ErrorEvent;
var Loader = require('../net/Loader.js').Loader;
var Response = require('../net/Response.js').Response;
var JsonRpcResponse = require('../jsonrpc/JsonRpcResponse.js').JsonRpcResponse;

/**
 * @class OpalLoader
 * @extends EventDispatcher
 * @requires OpalRequest
 * @requires Event
 * @requires ErrorEvent
 * @requires EventDispatcher
 *
 * @param {OpalRequest} request
 */
var OpalLoader = exports.OpalLoader = function (request) {
	this._opalRequest = null;
    Loader.call(this, request);
};

OpalLoader.prototype = Object.create(Loader.prototype);

OpalLoader.prototype.setRequest = function(request) {
	Loader.prototype.setRequest.call(this, request);
	if(request){
		this._opalRequest = request;
	}
}

OpalLoader.prototype.load = function(request) {
  Loader.prototype.load.apply(this, arguments);
  
  if (process.env['OPAL_IDENTITY']  && this._opalRequest && process.env['OPAL_IDENTITY'] != this._opalRequest.getApplication()) {
    console.warn('OpalLoader/IDENTITY_WARN: application: ' + process.env['OPAL_IDENTITY'] + ' is using different app name: ' + this._opalRequest.getApplication());
  }
}

OpalLoader.prototype._parseResponse = function (response) {
    var isJson = response.headers.hasOwnProperty('content-type') && response.headers['content-type'].indexOf('application/json') !== -1,
        data,
        body;

    if (isJson) {
        var json = this._buffer.toString();

        try {
            body = new JsonRpcResponse(JSON.parse(json));
        } catch (err) {
            this.dispatchEvent(new ErrorEvent(Loader.Event.ERROR, {json: json, error: (err.message || err)}, -4, 'OPAL Response JSON parse error'));
            return false;
        }
    } else if(response.statusCode != 200) {
        this.dispatchEvent(new ErrorEvent(Loader.Event.ERROR, {statusCode: response.statusCode}, -5, 'opal error, StatusCode not 200 -> '+ response.statusCode + ' origin: ' + response.headers['x-onet-trace']));
        return false;
    } else {
        body = new Response(this._buffer);
    }
    
    data = new OpalResponse({
        "statusCode": response.statusCode,
        "headers": response.headers,
        "httpVersion": response.httpVersion,
        "body": body
    });

    if (isJson) {
        this.dispatchEvent(new Event(OpalLoader.Event.JSON_RESPONSE, data));
    } else {
        this.dispatchEvent(new Event(OpalLoader.Event.HTTP_RESPONSE, data));
    }

    //zwracamy "blad" aby Loader oszukac dispatch Loader.Event.LOADED
    return false;
};

OpalLoader.Event = {};
OpalLoader.Event.JSON_RESPONSE = 'OpalLoader_JSON_RESPONSE';
OpalLoader.Event.HTTP_RESPONSE = 'OpalLoader_HTTP_RESPONSE';
