#ifndef __TNURLPOOL_H__
#define __TNURLPOOL_H__
#include "foundation/SharedPtr.h"
#include <vector>
#include "foundation/Mutex.h"

class TnUrl;
namespace Tn
{
    namespace Foundation
    {
        class Task;
    };
};
class TnUrlPool
{
	typedef struct tagConnectionNode
	{
		int time;
		Tn::Foundation::shared_ptr<TnUrl> tnurl;
	}ConnectionNode;
public:
	/**
	* Get instance of TnUrlPool, it's singleton
	*@return instance of TnUrlPool
	*/
	static TnUrlPool& GetInstance();

public:
	/**
	* Get handler of TnUrl
	* If there's existing handler with the same host as url described, it's returned
	* Otherwise, a new handler is returned
	*@param url expected url
	*@return handler of TnUrl
	*/
	Tn::Foundation::shared_ptr<TnUrl> Get(const std::string& url);

	/**
	* Release the handler of tnurl back to pool. 
	* The released handler will be stored in pool for new request to enable re-use of the same connection
	* Note: the handler will be invalid after the call
	*@param connection handler of TnUrl
	*/
	void Release(Tn::Foundation::shared_ptr<TnUrl>& connection);

	/**
	* Set timeout for idle connection, when time expires, the connection/handler will be removed from pool
	*@param timeInMs time in milliseconds
	*/
	void SetTimeout(int timeInMs);

	/**
	* Flush all cached connections. All cached connections will be removed immediately.
	* Used when network interface type changing
	*/
	void FlushPool();

private:
	TnUrlPool();
	TnUrlPool(const TnUrlPool&);
	TnUrlPool& operator=(const TnUrlPool&);
	~TnUrlPool();

	void OnTimeout();

private:
	std::vector<ConnectionNode>mNodes;
	Tn::Foundation::mutex mMutex;
	int mTimeout;
	int mFlushTime;
	Tn::Foundation::shared_ptr<Tn::Foundation::Task> mhTask;
	bool mTimerRunning;
};

#endif //!__TNURLPOOL_H__
