

//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
//_/_/
//_/_/  This file is part of CMSDK version 2.0.0.170915_Beta4 (15 September 2017)
//_/_/  
//_/_/  developed by
//_/_/  
//_/_/  Communicative Machines Ltd. 
//_/_/    http://cmlabs.com/
//_/_/  Copyright (c) 2017
//_/_/  
//_/_/  in collaboration with 
//_/_/  
//_/_/  Icelandic Institute for Intelligent Machines ses
//_/_/    Menntavegur 1
//_/_/    101 Reykjavik
//_/_/    ICELAND
//_/_/    http://www.iiim.is/
//_/_/
//_/_/  and is released under the following
//_/_/  
//_/_/  EXTENDED BSD License
//_/_/
//_/_/  Redistribution and use in source and binary forms, with or without
//_/_/  modification, is permitted provided that the following conditions 
//_/_/  are met:
//_/_/
//_/_/  - Redistributions of source code must retain the above copyright 
//_/_/    and collaboration notice, this list of conditions and the following 
//_/_/    disclaimer.
//_/_/
//_/_/  - Redistributions in binary form must reproduce the above copyright 
//_/_/    notice, this list of conditions and the following disclaimer in the 
//_/_/    documentation and/or other materials provided with the distribution.
//_/_/
//_/_/  - Neither the name of its copyright holders nor the names of its 
//_/_/    contributors may be used to endorse or promote products derived from 
//_/_/    this software without specific prior written permission.
//_/_/
//_/_/  - CADIA Clause: The license granted in and to the software under this 
//_/_/    agreement is a limited-use license. The software may not be used in 
//_/_/    furtherance of: (i) intentionally causing bodily injury or severe 
//_/_/    emotional harm to any person; (ii) invading the personal privacy or 
//_/_/    violating the human rights of any person; or (iii) committing or 
//_/_/    preparing for any act of war. 
//_/_/
//_/_/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
//_/_/  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
//_/_/  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
//_/_/  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 
//_/_/  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
//_/_/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
//_/_/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
//_/_/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
//_/_/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
//_/_/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
//_/_/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//_/_/
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
#if !defined(_REQUESTGATEWAY_H_)
#define _REQUESTGATEWAY_H_

#pragma once

#include "Stats.h"
#include "NetworkManager.h"
#include "RequestExecutor.h"
#include "RequestClient.h"


namespace	cmlabs{

/////////////////////////////////////////////////////////////
// RequestGateway
/////////////////////////////////////////////////////////////

class RequestGateway : public Runnable, public NetworkReceiver {
public:
	static bool UnitTest();

	friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg);
	friend THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg);

	RequestGateway(uint32 id);
	virtual ~RequestGateway();

	bool init(const char* sslCertPath = NULL, const char* sslKeyPath = NULL);

	bool setWebServerInfo(const char* name, const char* rootdir, const char* indexfile);
	bool setExternalAPILabel(const char* label);
	bool setInternalAPILabel(const char* label);
	bool setCacheFiles(bool cache);
	bool setResponseType(const char* type);
	bool setLongRequestLimit(uint32 limit);

	bool addPort(uint16 port, uint8 encryption, bool enableHTTP = false, uint32 timeout = 3000);

	bool addGateway(uint32 id, std::string addr, uint16 port);

	bool receiveNetworkEvent(NetworkEvent* evt, NetworkChannel* channel, uint64 conid);
	bool receiveMessage(DataMessage* msg, NetworkChannel* channel, uint64 conid);
	bool receiveHTTPRequest(HTTPRequest* req, NetworkChannel* channel, uint64 conid);

protected:
	bool runExec();
	bool runClient();

	bool callInternalAPI(const char* apiName, HTTPRequest* req, NetworkChannel* channel, uint64 conid);
	bool callExternalAPI(const char* apiName, HTTPRequest* req, NetworkChannel* channel, uint64 conid);

	std::list<RequestConnection> getTopExecutors(std::string requestString, uint32 reqSize, bool& isLongReq);
	bool sendToExecutor(RequestReply* reply);
	bool replyToClient(DataMessage* msg);

	NetworkManager* manager;
	NetworkChannel* channel;
	std::map<uint64,RequestConnection> executors;
	std::map<uint64,RequestConnection> clients;
	std::map<uint64,RequestConnection> webClients;
	utils::WaitQueue<RequestReply*> execQ;
	utils::WaitQueuePointer<DataMessage*> replyQ;
	std::map<uint64,RequestReply*> requestMap;
	std::vector<std::string> longReqNames;
	
	utils::Mutex mutex;
	//uint32 threadID;
	uint32 threadIDClient;
	uint64 lastRefID;
	uint64 clientSentCount;
	uint64 clientReceivedCount;
	uint64 execSentCount;
	uint64 execReceivedCount;

	uint32 id;
	uint16 port;
	uint32 longReqLimit;
	bool sslSupport;
	bool cacheFiles;
	bool replyXML;

	std::string webServerName;
	std::string rootdir;
	std::string indexFilename;

	std::string internalAPITitle;
	std::string externalAPITitle;

	MovingAverage shortAvgStats;
	MovingAverage longAvgStats;
	//std::map<uint64, MovingAverage> shortAvgStatsExec;
	//std::map<uint64, MovingAverage> shortAvgStatsClients;
	//std::map<uint64, MovingAverage> shortAvgStatsWeb;
	//std::map<uint64, MovingAverage> longAvgStatsExec;
	//std::map<uint64, MovingAverage> longAvgStatsClients;
	//std::map<uint64, MovingAverage> longAvgStatsWeb;
};

THREAD_RET THREAD_FUNCTION_CALL RequestGatewayExecRun(THREAD_ARG arg);
THREAD_RET THREAD_FUNCTION_CALL RequestGatewayClientRun(THREAD_ARG arg);

}

#endif // _REQUESTGATEWAY_H_
