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

#ifndef CDSCtlrFH
#define CDSCtlrFH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <stdio.h>
#include <ADODB.hpp>
#include <DB.hpp>
//---------------------------------------------------------------------------
#include "ITSLibF.h"
#include "CDSItsObjectF.h"
#include "CenterCommF.h"
#include "ITSLogF.h"
#include "VmsFormF.h"
#include "PacketHandllingF.h"
//---------------------------------------------------------------------------

/* 객체 사용여부 플래그 */
typedef enum en_object_state
{
    object_disable = 0,
    object_enable  = 1,
} EN_OBJECT_STATE;

/* BIT 사용여부 플래그 */
typedef enum en_bit_state
{
    bit_disable = 0,
    bit_enable  = 1,
} EN_BIT_STATE;

/* 사용여부 플래그 */
typedef enum _e_use_flag
{
    use_disable = 0,
    use_enable,
} e_use_flag;

/* 스레드 상태 플래그 */
typedef enum _e_thread_state
{
    thr_ready = 0,
    thr_run,
    thr_stop,
} e_thread_state;

/* 통신상태 플래그 */
typedef enum _e_comm_state
{
    comm_close = 0,
    comm_open,
} e_comm_state;

/* 제어기상태 플래그 */
typedef enum _e_ctlr_state
{
    state_normal = 0,
    state_error,
    state_unknown,
} e_ctlr_state;

typedef struct _THR_INFO
{
public:
    void Init()
    {
        useFlag         = use_enable;
        thrState        = thr_ready;
        commState       = comm_close;
        pThread         = NULL;
        activeIndicator = false;
    };

    BYTE        useFlag;          /* 스레드 사용 여부 */
    BYTE        thrState;         /* 스레드 상태 */
    BYTE        commState;        /* 통신 상태 */
    AnsiString  ConnectTm;
    AnsiString  DisconnectTm;

	void       *pThread;          /* 스레드 포인터 */
    bool        activeIndicator;  /* 스레드 실행 상태 */
} THR_INFO;
//---------------------------------------------------------------------------

// VMS 제어모드
typedef struct// vms_form_download
{
	BYTE        Control;                /* VMS 제어모드 */
	AnsiString  ManSceId;               /* 수동시나리오ID */
	AnsiString  EmeSceId;               /* 긴급시나리오ID */
	AnsiString  CurSceId;               /* 현재시나리오ID */

	bool        Enable;                 /* 활성화 여부 */
	int         MaxDisplayForm;         /* 최대 표출폼 갯수 */
	AnsiString  SvcDate;                /* 제공시각 */
	int         SaveFlag;               /* 제공정보 저장 여부 */
	TDateTime   pTimer;                 /* timer for provide */
    bool        Result;
    bool        Schedule;               /* 스케줄에 의한 다운로드 인 경우 */
} VMS_CONTROL_MODE;

// VMS 다운로드
#define VMS_MAX_DOWNLOAD                8       /* 최대 VMS 다운로드 */
typedef struct VmsDownLoadInfo
{
	bool        Enable;             	/* 활성화 여부 */
	int         SaveFlag;               /* 다운로드정보 저장 여부 */
	TDateTime   dTimer;                 /* timer for download */
	int         Count;                  /* 정보 갯수 */
	struct
    {
		AnsiString  RegDate;           	/* 등록일시 */
		AnsiString  FileType;          	/* 다운로드파일유형 */
		AnsiString  FileId;            	/* 다운로드파일ID */
		AnsiString  SendStartDate;     	/* 전송시작시각 */
		AnsiString  SendEndDate;       	/* 전송완료시각 */
		int         SendStep;           /* 전송진행단계 */
		int         SendResult;        	/* 전송결과 */
	} Unit[VMS_MAX_DOWNLOAD];
} VMS_DOWNLOAD_INFO;

typedef enum en_vms_downalod
{
    vms_download_disable = 0,
    vms_download_enable  = 1,
} EN_VMS_DOWNLOAD;

typedef enum en_vms_download_step
{
	send_wait,			/* 0:대기 */
	send_progress,		/* 1:전송중 */
	send_complete,      /* 2:전송완료 */
} EN_VMS_DOWNLOAD_STEP;

// 전송결과
typedef enum en_send_result
{
	send_result_fail,	/* 0:실패 */
	send_result_succ	/* 1:성공 */
} EN_SEND_RESULT;

//---------------------------------------------------------------------------
#define VMS_MAX_EVENT       16
typedef struct vms_event_detl
{
    AnsiString LINK_ID;
    AnsiString IFSC_ID;
    AnsiString VMS_IFSC_ID;
    AnsiString VMS_IFSC_NM;
    AnsiString DSPL_STRT_NODE_NM;
    AnsiString DSPL_END_NODE_NM;
    AnsiString DETR_ID;
    AnsiString DSPL_PRRT;
    AnsiString INCD_OCRR_ID;
    AnsiString STRT_LCTN_NM;
    AnsiString END_LCTN_NM;
    AnsiString OCRR_LCTN_NM;
    AnsiString VMS_INCD_TYPE_NM;
    AnsiString VMS_INCD_TYPE_CD;
    AnsiString VMS_INCD_DETL_NM;
    AnsiString VMS_INCD_DETL_TYPE_CD;
    AnsiString CMTR_GRAD_NM;
    AnsiString CMTR_GRAD_CD;
    AnsiString INCD_CLSR_LANE;
    AnsiString INCD_STRT_DT;
    AnsiString INCD_END_PRAR_DT;
    AnsiString ROAD_NM;
    AnsiString SPOT_NM;
    AnsiString VMS_INCD_RSTR_TYPE_CD;
    AnsiString VMS_INCD_RSTR_TYPE_NM;
    AnsiString INCD_TITL;
} VMS_EVENT_DETL;

typedef struct vms_event_info
{
    int            Count;
    VMS_EVENT_DETL Unit[VMS_MAX_EVENT];
} VMS_EVENT_INFO;
//---------------------------------------------------------------------------
#define VMS_MAX_SAFE        16
typedef struct vms_safe_detl
{
    AnsiString SAFE_ALM_ID; //재난안전 알람 ID(YYYYMMDDNNNNN)
    int        MSG_TP;      //표출메시지종류(2:2단메시지,3:3단메시지)
    AnsiString RGST_DT;     //등록 일시(YYYYMMDDHH24MISS)
    AnsiString ALM_STRT_DT; //방송시작시각(YYYYMMDDHH24MISS)
    AnsiString ALM_END_DT;  //방송종료시각(YYYYMMDDHH24MISS)
    AnsiString MSG_LN_1;    //재난안전문자 1열
    AnsiString MSG_LN_2;    //재난안전문자 2열
    AnsiString MSG_LN_3;    //재난안전문자 3열
} VMS_SAFE_DETL;

typedef struct vms_safe_info
{
    int           Count;
    VMS_SAFE_DETL Unit[VMS_MAX_SAFE];
} VMS_SAFE_INFO;
//---------------------------------------------------------------------------

#define VMS_MAX_SCHEDULE    INT_VMS_MAX_FORM
typedef struct vms_schedule_detl
{
    AnsiString VMS_SCH_TYPE;        //VARCHAR2(5)	N			VMS 스케줄 유형(A:자동,F:고정,B:기본)
    int        VMS_SCH_FORM_TYPE;   //NUMBER(3)	    N			VMS 폼 스케쥴 유형(0:교통,1:돌발,2:공사행사,3:홍보,4:우회,5:정체,6:안전,7:동영상,8:스트리밍영상)
    int        PHASE;               //NUMBER(2)	    N			PHASE
    AnsiString VMS_FORM_ID;         //NUMBER(5)	    Y			VMS FORM ID
    int        DSPL_HH;             //NUMBER(3)	    Y	0		표출 시간
    AnsiString DSPL_STRT_HH;        //VARCHAR2(14)	N			표출시작시간
    AnsiString DSPL_END_HH;         //VARCHAR2(14)	N			표출종료시간
    AnsiString FRST_VMS_IFSC_ID;    //NUMBER(10)	Y			1단 VMS 정보제공구간 ID
    AnsiString SECD_VMS_IFSC_ID;    //NUMBER(10)	Y			2단 VMS 정보제공구간 ID
    AnsiString THIR_VMS_IFSC_ID;    //NUMBER(10)	Y			3단 VMS 정보제공구간 ID
    AnsiString FOUR_VMS_IFSC_ID;    //NUMBER(10)	Y			4단 VMS 정보제공구간 ID
    AnsiString FRST_IMG_IFSC_ID;    //NUMBER(10)	Y			1단 이미지 정보제공구간 ID
    AnsiString SECD_IMG_IFSC_ID;    //NUMBER(10)	Y			2단 이미지 정보제공구간 ID
    AnsiString THIR_IMG_IFSC_ID;    //NUMBER(10)	Y			3단 이미지 정보제공구간 ID
    AnsiString FOUR_IMG_IFSC_ID;    //NUMBER(10)	Y			4단 이미지 정보제공구간 ID
    AnsiString SYMB_LIB_NMBR;       //NUMBER(4)	    Y	0		동영상인 경우 동영상 파일 심벌 아이디
    AnsiString STRM_ADDR;           //VARCHAR2(60)	Y			스트리밍인경우 스트리밍 주소

    AnsiString VMS_IFSC_ID;         //도형식 배경 하단 소통정보 제공구간 ID

    bool       DSPL_CNGS_YN;

    VMS_EVENT_DETL *EVENT;
    VMS_SAFE_DETL  *SAFE;           //재난안전
} VMS_SCHEDULE_DETL;

typedef struct vms_schedule_info
{
    int               Count;
    VMS_SCHEDULE_DETL Unit[VMS_MAX_SCHEDULE];
} VMS_SCHEDULE_INFO;
//---------------------------------------------------------------------------

#define VMS_MAX_CNGS_FORM   20

class TVmsIfsc
{
public:
    TVmsIfsc()
    {
        IsUsed    = true;
        CNGS_SPD  = 0;
        CNGST_CNT = 0;
        dtCngst   = Now();

        CNGS_CNFM_YN   = false;
        CNGS_CNFM_SPED = 0;
    };
    ~TVmsIfsc(){};
public:
    AnsiString VMS_IFSC_ID;         //NUMBER(10)	N			VMS 정보제공구간 ID
    int        DSPL_PRRT;           //NUMBER(2)	    Y			표출 우선순위
    AnsiString AXIS_YN;             //CHAR(1)	    Y	'N'		축정보 생성용
    int        CNGS_SPD;
    bool       CNGS_CNFM_YN;
    int        CNGS_CNFM_SPED;

    bool       IsUsed;
    int        CNGST_CNT;
    TDateTime  dtCngst;
};
//---------------------------------------------------------------------------

class TClientSession;

class TDownloadForm
{
public:
    TDownloadForm()
    {
    }
    ~TDownloadForm()
    {
    }

public:
    AnsiString  VMS_FORM_ID;             //NUMBER(5)	    N			VMS FORM ID
    TDateTime   DownloadTm;
    AnsiString  UPDT_DT;
    bool        AlreadyDownload;
public:
};
//---------------------------------------------------------------------------

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

private:
    CRITICAL_SECTION    FCS;

public:
    THR_INFO    Server;
    THR_INFO    Client;

    TThreadList *pPackQueue;    /* 패킷 버퍼 */

public:
    bool        Used;

    AnsiString  CTLR_NMBR;          //	N	NUMBER(10)	    N			제어기 번호

    AnsiString  CTLR_ID;            //	N	VARCHAR2(10)	Y			제어기 ID
    AnsiString  NM;                 //	N	VARCHAR2(40)	Y			명
    AnsiString  CTLR_IP;            //	N	VARCHAR2(20)	Y			제어기 아이피
    int         CTLR_PORT;          //	N	NUMBER(5)	    Y	0		제어기 포트
    int         GROUP_NO;
    int         CTLR_LOCAL_NO;      //	N	NUMBER(5)	    Y	0		제어기 지역번호
    AnsiString  TYPE_CD;            //	N	VARCHAR2(7)	    Y			유형 코드
    AnsiString  ISTL_LCTN_NM;       //	N	VARCHAR2(40)	Y			설치 위치 명
    double      X_CRDN;             //	N	NUMBER(11,8)	Y			X 좌표
    double      Y_CRDN;             //	N	NUMBER(10,8)	Y			Y 좌표
    AnsiString  DEL_YN;             //	N	CHAR(1)	        Y	'N'		삭제 여부

    TDateTime   dtConnect;
    TDateTime   dtDisConnect;
    DWORD       dwConnectCnt;

    ////////////////////////////// Private controller information
    int         WIDTH, HEIGHT;
    int         ROW_NUM, COL_NUM;
    int         MODL_ROW_NUM, MODL_COL_NUM;
    int         POWR_ROW_NUM, POWR_COL_NUM;

    int         VMS_MAX_PHSE_NUM;   //	N	NUMBER(2)	Y	14		VMS 최대 표출면 개수
    int         DEF_PHSE_CHNG_CYCL; //	N	NUMBER(3)	Y	5		기본메시지주기
    int         PANL_PWER_MODE;     //	N	NUMBER(3)	Y	2		전광판 전원 모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
    int         FAN_MODE;           //	N	NUMBER(3)	Y	2		FAN 동작모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
    int         FAN_RUN_TMPR;       //	N	NUMBER(3)	Y	30		팬 동작 온도
    int         HETR_MODE;          //	N	NUMBER(3)	Y	2		히터 동작모드(0x00:꺼짐,0x01:켜짐,0x02:자동,0x09:알수없음)
    int         HETR_RUN_TMPR;      //	N	NUMBER(3)	Y	0		히터 동작 온도
    int         BRGH_MODE;          //	N	NUMBER(3)	Y	2		휘도 모드(0x00:주간,0x01:야간,0x00:자동,0x09:알수없음)
    int         BRGH_CURR_STEP;     //	N	NUMBER(3)	Y	40		휘도 현재 단계(0~100)
    int         BRGH_WEEK_STEP;     //	N	NUMBER(3)	Y	64		휘도 주간 단계(0~100)
    int         BRGH_NGHT_STEP;     //	N	NUMBER(3)	Y	48		휘도 야간 단계(0~100)
    int         MODL_ERR_RATE;      //	N	NUMBER(3)	Y	10		VMS 모듈 오류 율
    int         CMNC_FAIL_RATE;     //	N	NUMBER(3)	Y	60		VMS 통신 오류 기본 값


    AnsiString  OPER_MODE;          //	N	VARCHAR2(7)	Y	'A'		운영 모드
    AnsiString  PANL_ON_TIME;       //	N	VARCHAR2(4)	Y	'0400'		전광판 ON TIME
    AnsiString  PANL_OFF_TIME;      //	N	VARCHAR2(4)	Y	'0200'		전광판 OFF TIME
    AnsiString  ParamResTime;

    int         PROTOCOL_VER;       // 구미시 텍스트, 도형식 프로토콜 구분을 위해 추가

    AnsiString          DownloadFormId;
    VMS_DOWNLOAD_DATA   FormDownload;
    TItsMap<AnsiString, TDownloadForm*> FDownloadLists;

    //////////////////////////////
    struct
    {
        bool        IsOnOff;
        BYTE        OnOff;
        AnsiString  PowerOnTime;    /* ON TIME */
	    AnsiString  PowerOffTime;   /* OFF TIME */
        int         Retry;
    } MODULE;

    struct
    {
        AnsiString  SchTime;
        int         Value;
        int         Retry;
    } LUMINANCE;

    VMS_SCHEDULE_INFO  *SCHEDULE;
    VMS_EVENT_INFO     *INCIDENT;
    VMS_EVENT_INFO     *EVENT;
    VMS_SAFE_INFO      *SAFE;

    VMS_DOWNLOAD_INFO  *DOWNLOAD;
    VMS_CONTROL_MODE   *CTRLMODE;

    TVmsFormManager    *pForms;

    bool                FSaveState;
    INT_VMS_STATE       DSTATE;
    INT_VMS_STATE       RSTATE;

    bool                FProvide;
    bool                FModeChange;

    bool                FIsOldProtocol;
    bool                FIsFtpDownload;
    bool                FIsProtolFontName;
    bool                FIsStatusAuto;
    AnsiString          VmsDownId;
    bool                FBmpDownload;

    bool                FSymbolDownload;
    bool                FExistCngsForm;     // 이번주기 정체폼을 다운로드 할게 존재하는지 여부
    int                 FMaxCngsForm;        // 정체폼 생성 최대 갯수

    BYTE                FTxtOpCode;

    TItsMap<AnsiString, TVmsIfsc*> FIfscLists;
    //TItsMap<int, TVmsIfsc*> FIfscLists;   //우선순위를 키로 하는 경우
    //////////////////////////////

    AnsiString          CTLR_NMBR_ID;
    TClientSession     *FSession;
    AnsiString          LOGIN_IPADDR;
    TDateTime           tmStts;
    String              DSPL_DT;
    int                 PHASE;

public:
    bool        FDispLog;
    TITSLog    *FSLog;
    TITSLog    *FCLog;
    AnsiString  FFtpFormDir;
    AnsiString  FLocalFormDir;

    AnsiString MODL_STTS;
    AnsiString PWER_STTS;

public:
    void Lock();
    void UnLock();

    bool ChangedState(INT_VMS_STATE *DSTATE, INT_VMS_STATE *RSTATE);
    void InitDownLoadInfo();
    void InitCtrlMode();
    void InitEvent();
    void InitIncident();
    void InitSchedule();
    void InitSafe();

    void InitDownloadFileInfo();
};
//---------------------------------------------------------------------------

class TCDSCtlrManager : public TCDSItsObject
{
public:
    TCDSCtlrManager();
    ~TCDSCtlrManager();

private:

public:
    int Total;
    int Error;
    int Normal;
    int Module;

    int FCtlrStts5Min;

    TItsMap<AnsiString, TCDSCtlr*> FLists;

public:
    int GetCount() { return FLists.Size(); }
    void InitProvide(TCDSCtlr *AObj=NULL);

    __property int Count = { read = GetCount };

public:
    void InitProvide();

public:
    int LoadCtlrInfo(TADOConnection *ADbConn);
    int LoadCtlrStts(TADOConnection *ADbConn);
    int SaveCtlrStts(TADOConnection *ADbConn, void *AData);
    int SaveCtlrIpAddr(TADOConnection *ADbConn, void *AData);
    int SaveCtlrSttsAll(TADOConnection *ADbConn);
    int SendCtlrSttsAll();

    int SaveCtlrParam(TADOConnection *ADbConn, void *AData);
};
//---------------------------------------------------------------------------
extern TCDSCtlrManager *CDSCtlrManager;
typedef std::map<AnsiString, TCDSCtlr*>::iterator CtlrItr;
//---------------------------------------------------------------------------

#define LOCK_FOR_CTLR(_obj)                                                                                                   \
    {                                                                                                                         \
        TItsAutoLock lock(CDSCtlrManager->FLists.GetLock());                                                               \
        for(CtlrItr it=CDSCtlrManager->FLists.FObjects.begin(); it != CDSCtlrManager->FLists.FObjects.end(); ++it) \
        {                                                                                                                     \
            TCDSCtlr *_obj = (TCDSCtlr*)it->second;

#define LOCK_FOR_CTLR_END                   \
        }                                   \
    }

#define FOR_CTLR                                                                                                 \
    {                                                                                                            \
        CtlrItr it;                                                                                         \
        for(it=CDSCtlrManager->FLists.FObjects.begin(); it != CDSCtlrManager->FLists.FObjects.end(); ++it) \
        {                                                                                                        \
            TCDSCtlr *pObj = (TCDSCtlr*)it->second;

#define FOR_CTLR_END    \
        }               \
    }


#endif

