#ifndef _CEGODBTHREADPOOL_H_INCLUDED_
#define _CEGODBTHREADPOOL_H_INCLUDED_
///////////////////////////////////////////////////////////////////////////////
//                                                         
// CegoDbThreadPool.h  
// ------------------
// Cego db threadpool class definition
//                                                        
// Design and Implementation by Bjoern Lemke
//
// (C)opyright 2000-2019 Bjoern Lemke
//
// INTERFACE MODULE
//
// Class: CegoDbThreadPool
//
// Description: Managing the database threads
//
// Status: CLEAN
//
///////////////////////////////////////////////////////////////////////////////

#include <lfcbase/Chain.h>
#include <lfcbase/ListT.h>
#include <lfcbase/NetHandler.h>

#include "CegoDbThread.h"
#include "CegoBufferPool.h"
#include "CegoLockHandler.h"
#include "CegoDbHandler.h"

class CegoDbThread;

class CegoDbThreadPool : public Thread {
    
 public:

    enum ThreadState { STARTING, READY, CONNECTED, BUSY };
  
    CegoDbThreadPool();
    CegoDbThreadPool(int poolLimit, CegoDatabaseManager *pDBMng, CegoDbHandler::ProtocolType protType);
    ~CegoDbThreadPool();

    void* job(void* arg);

    void syncToReady();

    void loadObjects(int tabSetId);
    void unloadObjects(int tabSetId);
    void invalidateObject(int tabSetId, const Chain& objName, CegoObject::ObjectType type);

    int getPoolLimit() const;

    void getThreadInfo(int i, unsigned long long& numRequest, unsigned long long& numQueryRequest, unsigned long long& threadLoad, unsigned long long& allocatedSort, ThreadState& state, Chain& action);
    void setState(int i, ThreadState state);
    void incNumRequest(int i);
    void incNumQueryRequest(int i);

    void addThreadIdle(int i, unsigned long long usec);

    void setTid(int i, unsigned long long tid);
    void setThreadState(int i, CegoDbThreadPool::ThreadState state);
    void abortThread(int i);

    NetHandler* nextRequest();

    bool isTerminated();

    void getLockStat(Chain& lockName, int& lockCount, unsigned long long &numRdLock, unsigned long long &numWrLock, unsigned long long &sumRdDelay, unsigned long long &sumWrDelay);

    void P(int i);
    void V(int i);

 private:

    void lockQueue();
    void unlockQueue();

    unsigned long long* _threadId;
    ThreadState* _threadState;
    unsigned long long* _numRequest;
    unsigned long long* _numQueryRequest;
    unsigned long long* _threadIdle[THRMNG_NUMLOADSAMPLE];
    unsigned long long* _threadLoad;
    int _samplePos;
    CegoDbThread** _threadList;

    int _poolLimit;
    int _dataPortNo;
    int _maxSendLen;
    Chain _dataHostName;

    bool _terminated;
    bool _joined;

    ListT<NetHandler*> _requestQueue;

    CegoDatabaseManager* _pDBMng;
    CegoDbHandler::ProtocolType _protType;

    unsigned long _modId;
};

#endif
