/***************************************************************************
                   Work Pool Class Header ( WorkPool.h )
                -----------------------------------------

	begin      : 2013/06/04
	copyright  : (C) 2013 Solbox Inc.
	author     : Development 1 Team
					- 2013/06/04 - 1st dadamin
	email      : dev1@solbox.com
	version    : 3.2.0

	CopyRight(C) 2005 Solbox Inc. All Rights reserved.
	Redistribution and use in source and binary forms, with or with out
	modification, are not permitted in outside of Solbox Inc.
***************************************************************************/
#ifndef __WORK_POOL_H__
#define __WORK_POOL_H__

class CDBManager;
class CWorkPool;
class CInsertData;

class CWorkThread
{
public:
	CWorkThread();
	~CWorkThread();

	bool CreateWorkThread( CWorkPool* pools, CDBManager * manager );
	void Running();
	void Completed();
	void Stop();

	void RunWork(int client, string ipstr);
	void RunWork(string path);	

	inline void	SetPoolKey(int key)	{ m_key = key; }
	inline int	GetPoolKey()		{return m_key; }
protected:
	void WaitSignal();
	void ReleasePool();

	bool ReadFromSocket();
	bool ReadFromFile();

	bool GetXNLElementValue(const Node* node, string elmentName, string & ret);
	
	typedef multimap< string, CInsertData > InsertDataMap;

	bool	GetServiceInfo(const Node* node, InsertDataMap::iterator &iter);
	bool	GetStatData(const Node* node, InsertDataMap::iterator &iter);
	bool	GetStatSubList(const Node* node, InsertDataMap::iterator &iter);
	int		GetStatSubData(string statType, const Node* node, InsertDataMap::iterator &iter);
	bool	GetStatTimeValue(string statType, const Node* node, InsertDataMap::iterator &iter);
	bool	GetStatValue(string statType, const Node* node, InsertDataMap::iterator &iter);
	bool	GetFailData(const Node* node, InsertDataMap::iterator &iter);
	bool	GetFailDatabaseList(const Node* node, InsertDataMap::iterator &iter);
	bool	GetFailDatabaseType(const Node* node, InsertDataMap::iterator &iter);
	bool	DataParsing(Document *doc);

	void	SetUsedDB(CInsertData &idata, vector<string> & odata);

	bool ReadData();
	bool XMLParser();
	bool InsertData();
	int WriteFailLog();

private:
	static void* WorkFn(void*);

	enum WORK_DATA {
		UNKNOWN		=  -1,
		SOCKET_DATA	=	0,
		FILE_DATA	=	1,
	};

	enum WORK_DATA	m_datatype;
	int				m_clientfd;
	string			m_clientip;
	string			m_filename;

	pthread_mutex_t m_lock;
	pthread_cond_t	m_cond;

	bool	m_stop;

	CDBManager* m_dbManager;
	CWorkPool* m_pools;
	int m_key;
	
	string m_readdata;

	InsertDataMap m_insertdata;
};

class CWorkPool
{
public:
	CWorkPool();
	~CWorkPool();

	bool CreatePool(int size, CDBManager * manager);
	void Finalized();

	CWorkThread*	GetWork();
	void			ReleaseWork(CWorkThread * work);	

protected:

private:
	int		m_size;
	bool	m_exit;

	pthread_mutex_t m_lock;
	multimap<int, CWorkThread*> m_pools; 
};


#endif // __WORK_POOL_H__
