'use strict';
var topiarist = require('topiarist');
var Trade = require('caplin/trading/trademodel/Trade');
var TradeMessageServiceStub = require('caplin/trading/testing/TradeMessageServiceStub');
var TradeLegFactory = require('caplin/trading/trademodel/TradeLegFactory');
var TradeFactory = require('caplin/trading/trademodel/TradeFactory');
var StateMachineFactory = require('caplin/trading/statemachine/StateMachineFactory');
var ServiceRegistry = require('caplin/core/ServiceRegistry');

function ESPTradeFactory() {
	// XMLResourceService - to retrieve XML trade model from XML bundle.
	var oXmlResourceService = ServiceRegistry.getService('br.xml-service');
	var eTradeModelNode = oXmlResourceService.getXmlDocument('tradeModels')[0];
	this._stateMachineFactory = new StateMachineFactory();
	this._stateMachineFactory.loadModelsFromXmlElement(eTradeModelNode);
}

topiarist.extend(ESPTradeFactory, TradeFactory);
topiarist.inherit(ESPTradeFactory, TradeLegFactory);

ESPTradeFactory.prototype.createNewTrade = function(mTradeParameters) {
	var sTradingProtocol = mTradeParameters.TradingProtocol;
	var sAssetClass = 'FX';
	var oTradeLegFactory = this;
	var sTradingType = 'SPOT';
	var oStateMachine = this._stateMachineFactory.getStateMachine('ESP');
	// Trade message service - to send and receive trade messages - temorary stub.
	this._tradeMessageService = new TradeMessageServiceStub();

	// Create a trade
	var oTrade = new Trade(sAssetClass,
	oTradeLegFactory, oStateMachine, this._tradeMessageService,
	sTradingProtocol, sTradingType, sAssetClass);
	// Add all trade details to the trade object e.g. instrument, buy/sell, price, etc.
	for (var sTradeField in mTradeParameters) {
		var sFieldValue = mTradeParameters[sTradeField];
		oTrade.setFieldValue(sTradeField, sFieldValue);
	}

	return oTrade;
};

ESPTradeFactory.prototype.createLeg = function() {
	// Not needed for this simple example.
};

module.exports = ESPTradeFactory;
