//---------------------------------------------------------------------------

#ifndef VMSCommLibFH
#define VMSCommLibFH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#ifndef __VMSCommLib_EXPORT__
#pragma comment(lib, "VMSCommLib.lib")
#endif // #ifndef __VMSCommLib_EXPORT__
//---------------------------------------------------------------------------
#include <vcl.h>

//COMMON LIBRARY
#include "ITSLogF.h"
#include "ITSNetF.h"


//DM
#include "DMAdoDbF.h"

//CDS
#include "CDSAtmpF.h"
#include "CDSColorF.h"
#include "CDSCtlrF.h"
#include "CDSFontF.h"
#include "CDSFormF.h"
#include "CDSIfscF.h"
#include "CDSImageF.h"
#include "CDSItsObjectF.h"
#include "CDSManagerF.h"
#include "CDSParkF.h"
#include "CDSProcessF.h"
#include "VmsFormF.h"
#include "VmsUtilsF.h"
#include "CDSVmsIfscTrafF.h"

//COMMON
#include "ClientSessionF.h"
#include "ClientSessionManagerF.h"
#include "FrmNetworkF.h"
#include "PacketHandllingF.h"

//THREAD
#include "DbmThreadF.h"
#include "JobThreadF.h"
#include "LogThreadF.h"

/*
******************************************************************************
* User Define
******************************************************************************
*/
#define SAFE_DELETE(p)      {if (p != NULL) { delete p; p = NULL; }}
#define MAINHANDLE          Application->MainForm->Handle

//---------------------------------------------------------------------------
#define MINFO(args...)      APP_LogWrite(ITSLog, eLOG_INFO,    log_sys, from_main, ##args)
#define MDATA(args...)      APP_LogWrite(ITSLog, eLOG_DATA,    log_sys, from_main, ##args)
#define MERROR(args...)     APP_LogWrite(ITSLog, eLOG_ERROR,   log_sys, from_main, ##args)
#define MWARN(args...)      APP_LogWrite(ITSLog, eLOG_WARNING, log_sys, from_main, ##args)
#define MDEBUG(args...)     APP_LogWrite(ITSLog, eLOG_DEBUG,   log_sys, from_main, ##args)
#define MDETAIL(args...)    APP_LogWrite(ITSLog, eLOG_DETAIL,  log_sys, from_main, ##args)

#define LINFO(args...)      LogWrite(eLOG_INFO,    ##args)
#define LDATA(args...)      LogWrite(eLOG_DATA,    ##args)
#define LERROR(args...)     LogWrite(eLOG_ERROR,   ##args)
#define LWARN(args...)      LogWrite(eLOG_WARNING, ##args)
#define LDEBUG(args...)     LogWrite(eLOG_DEBUG,   ##args)
#define LDETAIL(args...)    LogWrite(eLOG_DETAIL,  ##args)

#define SINFO(args...)      SysLogWrite(eLOG_INFO,    ##args)
#define SDATA(args...)      SysLogWrite(eLOG_DATA,    ##args)
#define SERROR(args...)     SysLogWrite(eLOG_ERROR,   ##args)
#define SWARN(args...)      SysLogWrite(eLOG_WARNING, ##args)
#define SDEBUG(args...)     SysLogWrite(eLOG_DEBUG,   ##args)
#define SDETAIL(args...)    SysLogWrite(eLOG_DETAIL,  ##args)

#define __MYFUNC__          (strrchr(__FUNCTION__, ':') ? strrchr(__FUNCTION__, ':')+1 : __FUNCTION__)

#define DBERROR(_class,_error,_sql) \
    ITSLog->LogDbError(String(__FUNCTION__),_class,_error,_sql,__FILE__, String(__FUNC__), __LINE__,false); \
    ErrorString = __FUNCTION__ + _error

#define LOGMSGLEN           30
#define DDBSTART            MDEBUG("DCOM %30.30s: Start", __MYFUNC__)
#define DDBSTOP(x)          MDEBUG("DCOM %30.30s: %d EA", __MYFUNC__, x)
#define IDBSTART            MINFO ("DCOM %30.30s: Start", __MYFUNC__)
#define IDBSTOP(x)          MINFO ("DCOM %30.30s: %d EA", __MYFUNC__, x)

#define WM_THREAD_TERMINATE         (WM_USER+0x92)      /* Thread 종료 메시지 */
#define WM_PROCESS_STATE            (WM_USER+0xA4)      /* 프로세스 상태 입력 */
//---------------------------------------------------------------------------

// SendMessageTimeout
#define     SEND_LOGMSG(a,b,c,d,e,f,g)  ::SendMessageTimeout(a, b, (WPARAM)c, (LPARAM)d, e, f, &g)
//#define     SEND_LOGMSG(a,b,c,d,e,f,g)  ::PostMessage(a, b, (WPARAM)c, (LPARAM)d)

#define     SEND_MSG(x,y,z,p)           ::SendMessage(x, y,       (WPARAM)z, (LPARAM)p)
#define     POST_MSG(x,y,z,p)           ::PostMessage(x, y,       (WPARAM)z, (LPARAM)p)
#define     USER_MSG(x,y,z)             ::PostMessage(x, WM_USER, (WPARAM)y, (LPARAM)p)

#define     WM_WINDOW_RESTORE           (WM_USER+0xA0)      /* 중복실행시 기존 윈도우 활성화 */

#define     WM_DB_THREAD                (WM_USER+0xF0)      /* DB 스레드 연계 메시지 */
#define     WM_THREAD                   (WM_USER+0xF1)      /* 스레드 연계 메시지 */
#define     WM_TCP_CLIENT               (WM_USER+0xF2)      /* TCP Client */
#define     WM_TCP_SERVER               (WM_USER+0xF3)      /* TCP Client */

#define     WM_TCP_THREAD               (WM_USER+0xF4)

#define     WM_TCP_SERVER_STTS          (WM_USER+0xB2)      // 제어기 접속/해제(통신스레드->메인)
#define     WM_TCP_CLIENT_STTS          (WM_USER+0xB3)      // 제어기 접속/해제(통신스레드->메인)
#define     WM_CTLR_STATE_STTS          (WM_USER+0xB4)      // 제어기 상태정보 업데이트

// 스레드 종료 대기 시간
#define     WAIT_THREAD_TERMINATE_TIME  5000    // Wait Thread Terminate Time(5 seconds)

/*
******************************************************************************
* 스레드로 전달하는 메시지
******************************************************************************
*/
#define     WM_EQUIP_STATE_ALL          (WM_USER+0xB2)      /* 시설물상태 개별 입력 */
#define     WM_EQUIP_STATE              (WM_USER+0xC2)      /* 시설물상태 전체 입력 */

#define     WM_DATABASE_CLOSE           (WM_USER+0xA0)      /* DATABASE CLOSE */
#define     WM_DATABASE_REFLASH         (WM_USER+0xA1)      /* DATABASE REFLASH */
#define     WM_DATABASE_OPEN            (WM_USER+0xA2)      /* DATABASE OPEN */
#define     WM_LOG_DISPLAY              (WM_USER+0xA3)      /* LOG DISPLAY */

#define     WM_MASTER_FORM              (WM_USER+0xD1)      /* 폼정보 변경 */
#define     WM_MASTER_IMAGE_SYMBOL      (WM_USER+0xD2)      /* 폼이미지정보 변경 */
#define     WM_MASTER_IMAGE_TRAFFIC     (WM_USER+0xD3)      /* 폼이미지소통정보 변경 */
#define     WM_MASTER_VMS_IFSC          (WM_USER+0xD4)      /* VMS IFSC 정보 변경 */

#define     WM_DATA_SAVE                (WM_USER+0xA8)      /* 데이터 저장 */
#define     WM_GET_ONOFF                (WM_USER+0xA9)      /* VMS ON/OFF */
#define     WM_PROVIDE_PROC             (WM_USER+0xAA)      /* VMS 교통정보 */
#define     WM_PROVIDE_SAVE             (WM_USER+0xAB)      /* VMS 제공정보 저장 */

#define     WM_MAKE_DOWNLOAD_FORM       (WM_USER+0xAD)      /* VMS 다운로드폼 생성 */
#define     WM_SAVE_DOWNLOAD_FORM       (WM_USER+0xAE)      /* VMS 다운로드폼 저장 */

/*
******************************************************************************
* User Define
******************************************************************************
*/
typedef struct tagThreadInfo
{
    TThread     *pThread;
    DWORD        dwThreadId;
    unsigned int nHandle;
    bool         bRunning;
public:
    void Clear()
    {
        pThread    = NULL;
        dwThreadId = 0;
        nHandle    = 0;
        bRunning   = false;
    }
} THREAD_INFO;
//---------------------------------------------------------------------------

typedef struct tagDatabaseInfo
{
    String  sProvider;
    String  sServerName;
    String  sCatalog;
    String  sUserName;
    String  sPassword;
    String  sConnectStr;
public:
    void Clear()
    {
        sProvider   = "";
        sServerName = "";
        sCatalog    = "";
        sUserName   = "";
        sPassword   = "";
        sConnectStr = "";
    }
    void MakeConnString()
    {
        sConnectStr  = "";
        sConnectStr += "Provider="         + sProvider;
        sConnectStr += ";Password="        + sPassword;
        sConnectStr += ";Persist Security Info=True";
        sConnectStr += ";User ID="         + sUserName;
        if (sCatalog != "")
        {
            sConnectStr += ";Initial Catalog=" + sCatalog;
        }
        sConnectStr += ";Data Source="     + sServerName;
    }
} DATABASE_INFO;

typedef enum _e_log_target
{
    log_sys,
    log_com,
    log_stop,
} e_log_taraget;

typedef enum _e_log_from
{
    from_main,
    from_dbms,
    from_srvTcp,
    from_cliTcp,
} e_log_from;

typedef struct tagIpcLogMessage
{
    int         From;
    int         Target;
    int         Kind;
    int         Flag;
    bool        Write;
    TDateTime   Tm;
    char        Type;
    void       *Obj;
    void       *Ctlr;

    char        Msg[MAX_LOG_BUFFER];
    int         Len;
} IPC_LOG_MESSAGE;

typedef enum _e_dbm_command
{
    dbm_status,
    dbm_initialize,
    dbm_save_unit_stts,
    dbm_save_unit_stts_hs,
    dbm_save_ctlr_stts,
    dbm_save_ctlr_stts_all,
    dbm_save_ctlr_stts_hs,
    dbm_dnld_form_cycle,
    dbm_dnld_form_mode,
    dbm_load_onoff_time,
    dbm_load_download_job,
    dbm_save_form_download,
    dbm_provide_result,

    dbm_parma_res,

    dbm_master_symbol_image,
    dbm_master_symbol_traffic,
    dbm_master_form,
    dbm_master_vms_ifsc,

    dbm_check_db_alive,

    dbm_dnld_form_init,

} e_dbm_command;
//---------------------------------------------------------------------------

#define MAX_VMS_PROVIDE_RESULT  100
typedef enum _e_vms_provide_result
{
    provide_form,
    provide_download,
    param_res,
} e_vms_provide_result;
//---------------------------------------------------------------------------

typedef struct tagVmsProvideRes
{
	BYTE    Type;                          /* 저장유형 */
	BYTE    Count;                         /* 정보 갯수 */
	void   *pObj[MAX_VMS_PROVIDE_RESULT];
} VMS_PROVIDE_RESULE;
//---------------------------------------------------------------------------

typedef struct tagCtlrStts
{
    int   Type;
    void *ObjPtr;
} CTLR_STTS;
//---------------------------------------------------------------------------

typedef struct tagIpcDbmMessage
{
    e_dbm_command   Command;
    int             Size;
    union
    {
        char                Data[1020];
        VMS_PROVIDE_RESULE  provide;
        CTLR_STTS           ctlr_stts;
    } U;
} IPC_DBM_MESSAGE;
//---------------------------------------------------------------------------

typedef struct tagCommConfig
{
    int             nCenterPort;        // center udp port

    short           nListenPort;        // vms listen port
    AnsiString      sLocalDomain;       // vms server domain

    int             nClientPort;        // vms controller connect port
    AnsiString      sLoginUser;         // vms controller login id

    int             nConnectWait;
    int             nCmdTimeOut;
    int             nWatchDogTime;
    int             nPollingTime;
    void Clear()
    {
    }
} COMM_CONFIG;
//---------------------------------------------------------------------------

#define Q_CLOSE         0xFFFFFFFE
#define Q_TICK          0xFFFFFFFF
#define MAX_TCP_BUFF    4096

typedef enum _e_tcp_msg
{
    eTcpConnect,
    eTcpClose,
    eTcpRecv,
    eTcpSend,
    eTcpErrorEvent,
    eTcpErrorRecv,
    eTcpErrorSend,
    eTcpSchedule,
    eTcpCloseAll,

    // VMS 제어 메시지
    eVmsLoginReq,
    eVmsFormDownload,
    eVmsScenarioDownload,
    eVmsParamReq,
    eVmsLedPowerControl,
    eVmsFanPowerControl,
    eVmsBrghSet,
    eVmsConfigSet,
    eVmsTimeControl,
    eVmsReset,
} e_tcp_msg;

typedef struct _ipc_job_message
{
    int   Type;
    DWORD ObjPtr;
    int   Len;
    char  Buff[MAX_TCP_BUFF];
} IPC_JOB_MESSAGE;

typedef struct tagAppConfig
{
    String          sConfigFile;
    bool            bAppClose;
    bool            bAppLoad;
    bool            bThrExit;
    bool            bThrJobExit;
    HANDLE          hFinishEvent;

    String          sTitle;
    long            lMainWinHandle;     /* Main Window Handle */

    AnsiString      sProcessId;       	/* Process ID */
    int             nProcessId;
    int             nProcessPort;

    AnsiString      sSystemId;          /* System ID */

    AnsiString      sLogDay;

    int             nTrafficCycleTime;
    int             nTrafficBasisTime;
    int             nSaveFormType;
    int             nDefaultFillColor;

    int             nMaxLogLines;

	int  MaxMemory;                     /* Max Memory size Mbyte */
	int  MaxHandle;                     /* Max Handle count */
	int  MaxThread;                     /* Max Thread count */
	int  MaxGdi;                        /* Max Gdi count */
    bool RcRestart;                     /* 리소스 오류시 재기동 여부 */

    bool DownloadBitmap;

    //THREAD_INFO     thrDb;              /* DB Thread */
    DATABASE_INFO   db;
    COMM_CONFIG     comm;

    bool            IsIpChecking;
    int             BottomTrafficCycle;
    int             BottomTrafficMaxCnt;
    bool            BottomTrafficCenter;
    int             CngsContCnt;
    bool            Traf1RowCenter;

    bool            IsImageSeqSave;

public:
    void Clear()
    {
        bThrExit       = false;
        bAppClose      = false;
        bAppLoad       = false;
        sTitle         = "";
        lMainWinHandle = 0;

        sProcessId  = "";
        sLogDay     = "";

        MaxMemory = 0;
        MaxHandle = 0;
        MaxThread = 0;
        MaxGdi    = 0;

        //thrDb.Clear();
        db.Clear();
        comm.Clear();
    }
} APP_CONFIG;

typedef struct tagGradeText
{
    AnsiString GRADE0;
    AnsiString GRADE1;
    AnsiString GRADE2;
    AnsiString GRADE3;
} GRADE_TEXT;

// system informations
typedef struct tagSystemInformation
{
    BYTE RunSts;            /* 동작 상태 */
    BYTE ComSts;            /* 통신 상태 */
    BYTE DbmSts;            /* DB 상태 */

    HANDLE hFinishEvent;    /* finish event */
	DWORD DbmThreadID;      /* DB 데이터 처리 스레드 ID */
	DWORD LogThreadID;     	/* LOG 데이터 처리 스레드 ID */
} SYSTEM_INFORMATION;
//---------------------------------------------------------------------------


/*
******************************************************************************
* Global variable definitions
******************************************************************************
*/
extern SYSTEM_INFORMATION *g_SysInfo;
extern bool                LOAD_DB;

extern APP_CONFIG  g_AppCfg;
extern LOG_INFO    g_LogCfg;
extern TITSLog    *ITSLog;

extern TItsNetQ    g_logQ;
extern TItsNetQ    g_dbmQ;
extern TItsNetQ    g_jobQ;

#define MAX_LOGQ_BUFF   256
#define MAX_DBMQ_BUFF   256
#define MAX_JOBQ_BUFF   512

extern TItsQBuff<IPC_LOG_MESSAGE, MAX_LOGQ_BUFF> g_logBuff;
extern TItsQBuff<IPC_DBM_MESSAGE, MAX_DBMQ_BUFF> g_dbmBuff;
extern TItsQBuff<IPC_JOB_MESSAGE, MAX_JOBQ_BUFF> g_jobBuff;

extern String           g_sAppDir ;       // Application Directory
extern String           g_sAppName;       // Program name
extern String           g_sCfgDir ;       // Program Config Directory
extern String           g_sLogDir ;       // Program Log Directory
extern String           g_sTempDir;       // Program Temp Directory
extern String           g_sImgDir;        // Program Image Directory


#define FTP_FORM    "FORM"
#define FTP_VIDEO   "VIDEO"
#define FTP_STATIC  "STATIC"
#define FTP_IMAGE   "IMAGE"

extern String          g_sFtpHomeDir ;  // FTP Home Directory
extern String          g_sFtpFormDir ;  // FTP Form Directory
extern String          g_sFtpVideoDir;  // FTP Video Directory
extern String          g_sFtpStaticDir; // FTP 정적폼 Directory
extern String          g_sFtpImageDir;  // FTP Image Directory

extern GRADE_TEXT      FIGURE;
extern GRADE_TEXT      TEXT;


/*
******************************************************************************
* Global function definitios
******************************************************************************
*/
int APP_LogWrite(void *ALogObj, int ALogKind, int ATarget, int AFrom, char *AFmt, ...);
int APP_PostDbThreadMessage(e_dbm_command ACommand, int ASize=0, void *AData=NULL);


#endif

