/*
*	©Copyright 2002-2003, Microsoft Corporation
*	Microsoft Confidential
*	Written by Sergey Vasilevskiy.
*/

/*
*	Platform-dependent SendToMarket class.
*/

#define ERR_TYPE_SEND_TO_MARKET 1000

//	Exception class for SendToMarket.
//
class CSendToMarketErr : public TPCE::CBaseErr
{
public:
	enum Action
	{
		eNone = 0,
		eMEENameDoesNotExist,
		eMEETableNotReceivedYet,
		eMEENameNotSpecified,

		eLast
	};

	CSendToMarketErr(int idMsg, char const * szLoc = NULL)
    : TPCE::CBaseErr(idMsg, szLoc)
	{
	}

	// A value which distinguishes the kind of error that occurred.
	//
	virtual int ErrorType() { return ERR_TYPE_SEND_TO_MARKET; }
	// A string (i.e., human readable) representation of the error.
	//
	virtual const char* ErrorText() const
	{
		static	char	*szMsgs[CSendToMarketErr::eLast+1] = {
			(char*)"Success",
			(char*)"MEE name does not exist.",
			(char*)"MEE table has not been received yet.",
			(char*)"Specify MEE driver to use (-m option) since more than one MEE has been launched.",

			// eLast
			//
			(char*)"Error code above the range"
		};

		if (m_idMsg > CSendToMarketErr::eLast || m_idMsg < CSendToMarketErr::eNone)
		{
			return szMsgs[CSendToMarketErr::eLast];
		}
		else
		{
			return szMsgs[m_idMsg];
		}
	}
};

class CSendToMarket : public TPCE::CSendToMarketInterface
{
	SOCKET				m_sockfd;	//to connect to Market Exchange Emulator
	PMEEIndexTable		m_pMEETable;	// pointer to SUT's MEE translation table
	const char*		    m_szMEEToUse;	// pointer to external buffer
	int					m_iMEEToUse;	// index in m_pMEETable of the MEE to use for SendToMarket
	
	void ThrowSystemError(char *szLocText)
	{
        throw new TPCE::CSystemErr(WSAGetLastError(), TPCE::CSystemErr::eNone, szLocText);
	}

	// Create TCP/IP socket and connect
	void CreateSocketAndConnect(char *szServer, unsigned short port, SOCKET &ret_sock);	

	void FindMEEToUse();

public:

	CSendToMarket(PMEEIndexTable pMEETable, const char* szMEEToUse)
	: m_pMEETable(pMEETable)
	, m_szMEEToUse(szMEEToUse)
	, m_iMEEToUse(0)
	{
		m_sockfd = INVALID_SOCKET;	// invalidate the socket array because there are no connections yet
	};

	~CSendToMarket()
	{
		if (m_sockfd != INVALID_SOCKET)
		{
			closesocket(m_sockfd);
		}
	}

    virtual bool SendToMarket(TPCE::TTradeRequest &trade_mes);	

};

