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

#include <vcl.h>
#include "ITSSkinF.h"
#//include "ITSUtilF.h"
#include "ITSDbF.h"
//#include "AppGlobalF.h"
#pragma hdrstop

#include "CFG0000MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtonEdit"
#pragma link "cxButtons"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxTextEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxCheckBox"
#pragma link "cxSpinEdit"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDBData"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridDBTableView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinsForm"
#pragma resource "*.dfm"

TCFG0000M *CFG0000M = NULL;


typedef struct tag_AppConfig
{
    String      sConfigFile;
    bool        bAppClose;
    long        lMainWinHandle;     /* Main Window Handle */
    String      sTitle;
    String      sProcessId;       	/* 프로세스 ID */
    String      sSkinName;
    bool        bSaveForm;
    bool        bLoginPrompt;
    String      sDefUseId;

    int         nLogLevel;
    AnsiString  sLogDay;
    bool        bDebug;

    struct
    {
        bool    Window;
        bool    Enabled;
        int     TimeOut;
    } Alarm;
    struct
    {
        bool    Window;
        bool    Enabled;
        int     TimeOut;
    } Incident;
    struct
    {
        int     AlarmValue;
    } Temp;

    struct
    {
        bool    Enabled;
        int     IntervalMin;
        bool    LogoutExit;
    } AutoLogout;

    struct
    {
        TThread     *pThread;
        DWORD        dwThreadId;
        unsigned int nHandle;
        bool         bRunning;
    } thr;
    struct
    {
        String  sProvider;
        String  sServerName;
        String  sUserName;
        String  sPassword;
        bool    bSqlLog;
    } itsdb;
    struct
    {
        String  sMainMap;
        String  sLinkMap;
    } flashmap;

    struct
    {
        String  sComModel;
        String  sDevModel;
    } vmscam;
} APP_CONFIG;

/*
*  전자지도 정보를 저장할 구조체
*/
typedef struct
{
    bool            bLoadL0;
    bool            bLoadL1;
    bool            bLoadL2;
    bool            bLoadL3;

    double          dCenterX;
    double          dCenterY;

    double          dLeftTopX;
    double          dLeftTopY;
    double          dRightBottomX;
    double          dRightBottomY;

    String          sCenterName;
    String          sMapFileNameL0;
    String          sMapFileNameL1;
    String          sMapFileNameL2;
    String          sMapFileNameL3;

    String          sIdxMapFileName;
} ST_GISINFO;

APP_CONFIG       g_AppCfg;
ST_GISINFO       g_GisInfo;

String           CenterCd = "";         // 지역센터 코드
String           CenterId = "";         // 지역센터 아이디
String           CenterName = "";       // 지역센터 명칭

int              g_nPid    = -1;        // Application Process ID
String           g_sAppDir = "";        // Application Directory
String           g_sAppName= "";        // Program name
String           g_sCfgDir = "";        // Config File Directory
String           g_sLogDir = "";        // Program Log Directory
String           g_sTempDir  = "";      // Program Temp Directory
String           g_sFormsDir = "";      // Program Forms Directory

//---------------------------------------------------------------------------
bool LoadConfigInfo()
{
    String   sCfgFile;
    TIniFile *pIniFile = NULL;

//    g_nPid = GetAppInfo(Application->ExeName, g_sAppDir, g_sProgNm);


    g_sAppDir  = ExtractFilePath(Application->ExeName);
    sCfgFile = g_sAppDir + "\\Cfg\\ITS_OP.ini";

    g_AppCfg.AutoLogout.Enabled = false;
    g_AppCfg.AutoLogout.IntervalMin = 0;
    g_AppCfg.AutoLogout.LogoutExit = false;

    g_AppCfg.thr.pThread    = NULL;
    g_AppCfg.thr.dwThreadId = 0;
    g_AppCfg.thr.nHandle    = 0;
    g_AppCfg.thr.bRunning   = false;

    g_AppCfg.bAppClose    = false;

    try
    {
        String sTmp;

        pIniFile = new TIniFile(sCfgFile);

        g_AppCfg.sTitle     = pIniFile->ReadString("APPLICATION", "TITLE",     "광역교통정보 교통관리시스템");
        g_AppCfg.sProcessId = pIniFile->ReadString("APPLICATION", "PROCESSID", "999999");

        g_AppCfg.sSkinName  = pIniFile->ReadString("APPLICATION", "SKINNAME", "Blue");
        if (g_AppCfg.sSkinName.IsEmpty()) g_AppCfg.sSkinName = "Blue";

        sTmp = pIniFile->ReadString("APPLICATION", "SAVEFORM", "1");
        g_AppCfg.bSaveForm = (sTmp == "1") ? true : false;

        sTmp = "0";//pIniFile->ReadString("DEFAULT", "LOGINPROMPT", "1");
        g_AppCfg.bLoginPrompt = (sTmp == "1") ? true : false;
        g_AppCfg.sDefUseId = pIniFile->ReadString("APPLICATION", "LASTUSER", "");

        sTmp = pIniFile->ReadString("AUTOLOGOUT", "ENABLED", "0");
        g_AppCfg.AutoLogout.Enabled = (sTmp == "1") ? true : false;
        sTmp = pIniFile->ReadString("AUTOLOGOUT", "INTERVALMIN", "10");
        g_AppCfg.AutoLogout.IntervalMin = sTmp.ToIntDef(0);
        if (g_AppCfg.AutoLogout.IntervalMin == 0) g_AppCfg.AutoLogout.IntervalMin = 10;
        sTmp = pIniFile->ReadString("AUTOLOGOUT", "LOGOUTEXIT", "0");
        g_AppCfg.AutoLogout.LogoutExit = (sTmp == "1") ? true : false;

        g_AppCfg.itsdb.bSqlLog     = false;
        g_AppCfg.itsdb.sProvider   = pIniFile->ReadString("ITSDB", "PROVIDER",   "OraOLEDB.Oracle.1");
        g_AppCfg.itsdb.sServerName = pIniFile->ReadString("ITSDB", "SERVERNAME", "HANTE");
        g_AppCfg.itsdb.sUserName   = pIniFile->ReadString("ITSDB", "USERNAME",   "hnits");
        g_AppCfg.itsdb.sPassword   = pIniFile->ReadString("ITSDB", "PASSWORD",   "hnits");
        String sSqlLog             = pIniFile->ReadString("ITSDB", "SQLLOG", "0");
        if (sSqlLog == "1") g_AppCfg.itsdb.bSqlLog = true;

        CenterId   = pIniFile->ReadString("CENTER", "CENTERID",   "L01");
        CenterName = pIniFile->ReadString("CENTER", "CENTERNAME", "중앙센터");
        CenterCd   = String(StrToInt(CenterId.SubString(2, 2)));

        // GIS 설정정보 로딩
        String sLeftTopX     = pIniFile->ReadString("MAP", "LEFTTOPX",     "126.891");
        String sLeftTopY     = pIniFile->ReadString("MAP", "LEFTTOPY",     "037.383");
        String sRightBottomX = pIniFile->ReadString("MAP", "RIGHTBOTTOMX", "126.981");
        String sRightBottomY = pIniFile->ReadString("MAP", "RIGHTBOTTOMY", "037.318");
        String sCenterX      = pIniFile->ReadString("MAP", "CENTERX",      "126.935");
        String sCenterY      = pIniFile->ReadString("MAP", "CENTERY",      "037.360");

        g_GisInfo.dLeftTopX     = sLeftTopX.ToDouble();
        g_GisInfo.dLeftTopY     = sLeftTopY.ToDouble();
        g_GisInfo.dRightBottomX = sRightBottomX.ToDouble();
        g_GisInfo.dRightBottomY = sRightBottomY.ToDouble();
        g_GisInfo.dCenterX      = sCenterX.ToDouble();
        g_GisInfo.dCenterY      = sCenterY.ToDouble();

        g_GisInfo.sCenterName     = CenterName;
        g_GisInfo.sIdxMapFileName = "";
        g_GisInfo.sMapFileNameL0  = pIniFile->ReadString("MAP",  "MAPFILEL0", "");
        g_GisInfo.sMapFileNameL1  = pIniFile->ReadString("MAP",  "MAPFILEL1", "");
        g_GisInfo.sMapFileNameL2  = pIniFile->ReadString("MAP",  "MAPFILEL2", "");
        g_GisInfo.sMapFileNameL3  = pIniFile->ReadString("MAP",  "MAPFILEL3", "");

        g_GisInfo.bLoadL0 = true;
        g_GisInfo.bLoadL1 = true;
        g_GisInfo.bLoadL2 = true;
        g_GisInfo.bLoadL3 = true;
        if (g_GisInfo.sMapFileNameL0 == "") g_GisInfo.bLoadL0 = false;
        if (g_GisInfo.sMapFileNameL1 == "") g_GisInfo.bLoadL1 = false;
        if (g_GisInfo.sMapFileNameL2 == "") g_GisInfo.bLoadL2 = false;
        if (g_GisInfo.sMapFileNameL3 == "") g_GisInfo.bLoadL3 = false;
    }
    __finally
    {
        if (pIniFile) delete pIniFile;
        pIniFile = NULL;
    }

    return true;
}
//---------------------------------------------------------------------------

__fastcall TCFG0000M::TCFG0000M(TComponent* Owner)
    : TForm(Owner)
{
    ITSSkin_Initialize(Application);

    ITSSkin_Load(this);

    FTitle = "환경설정";
    Caption = "통합운영단말 " + FTitle;
    LblCaption->Caption = FTitle;
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TCFG0000M::CommClose()
{
}
//---------------------------------------------------------------------------

/*
 * Form이 메모리에서 생성될때 호출되는 생성자 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TCFG0000M::FormCreate(TObject *Sender)
{
    LoadConfigInfo();
}
//---------------------------------------------------------------------------

/*
 * Form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TCFG0000M::FormShow(TObject *Sender)
{
    Refresh();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

/*
 * Form이 Show되고 난 후 최초 1회 수행되는 타이머 이벤트
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TCFG0000M::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
    RefreshData();
}
//---------------------------------------------------------------------------

/*
 * Refresh Data Event Function
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TCFG0000M::RefreshData()
{
    // 정보를 읽어와서 표출하자.
    EdCenterId->Text   = CenterId;
    EdCenterName->Text = CenterName;
    EdGisFile->Text    = g_GisInfo.sMapFileNameL0;
    EdDbProvider->Text = g_AppCfg.itsdb.sProvider;
    EdDbUser->Text     = g_AppCfg.itsdb.sUserName;
    EdDbSource->Text   = g_AppCfg.itsdb.sServerName;
    EdDbPasswd->Text   = g_AppCfg.itsdb.sPassword;
    EdProcessId->Text  = g_AppCfg.sProcessId;
    //EdTaskId->Text     = "";
    //EdNodeId->Text     = "";
    //EdSequence->Text   = "";

    ChkSaveForm->Checked   = g_AppCfg.bSaveForm;
    ChkAutoLogout->Checked = g_AppCfg.AutoLogout.Enabled;
    SeInterevalMin->Value  = g_AppCfg.AutoLogout.IntervalMin;
}
//---------------------------------------------------------------------------

/*
 * Close 버튼 클릭 이벤트 핸들러
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TCFG0000M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

/*
 * Select Button Click Event Handler
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TCFG0000M::BtnSaveClick(TObject *Sender)
{
    //bool   bSaved = false;
    String sMsgString;
    String sID, sIPAddress;
    int sMsgType = MB_OK|MB_ICONWARNING|MB_APPLMODAL;

    sMsgString = "시스템 환경설정 정보를 저장하시겠습니까?";

    sMsgType = MB_YESNO|MB_ICONINFORMATION|MB_APPLMODAL;
    if (Application->MessageBox(sMsgString.c_str(), FTitle.c_str(), sMsgType)==IDNO)
    {
        return;
    }

    String sCenterId   = EdCenterId->Text.Trim();
    String sCenterName = EdCenterName->Text.Trim();
    String sGisFile    = EdGisFile->Text.Trim();
    String sDbProvider = EdDbProvider->Text.Trim();
    String sDbUser     = EdDbUser->Text.Trim();
    String sDbSource   = EdDbSource->Text.Trim();
    String sDbPasswd   = EdDbPasswd->Text.Trim();
    String sProcessId  = EdProcessId->Text.Trim();
    g_AppCfg.bSaveForm = ChkSaveForm->Checked;
    String sSaveForm   = g_AppCfg.bSaveForm ? "1" : "0";

    //String sTaskId     = EdTaskId->Text.Trim();
    //String sNodeId     = EdNodeId->Text.Trim();
    //String sSequence   = EdSequence->Text.Trim();

    g_AppCfg.AutoLogout.Enabled = ChkAutoLogout->Checked;
    g_AppCfg.AutoLogout.IntervalMin = SeInterevalMin->Value;
    String sAutoLogout = g_AppCfg.AutoLogout.Enabled ? "1" : "0";
    String sInterMin   = String(g_AppCfg.AutoLogout.IntervalMin);
    try {
        SetConfigValue("CENTER",  "CENTERID",   sCenterId);
        SetConfigValue("CENTER",  "CENTERNAME", sCenterName);

        SetConfigValue("MAP",   "MAPFILEL0",  sGisFile);

        SetConfigValue("ITSDB", "PROVIDER",   sDbProvider);
        SetConfigValue("ITSDB", "SERVERNAME", sDbSource);
        SetConfigValue("ITSDB", "USERNAME",   sDbUser);
        SetConfigValue("ITSDB", "PASSWORD",   sDbPasswd);

        SetConfigValue("AUTOLOGOUT", "ENABLED",     sAutoLogout);
        SetConfigValue("AUTOLOGOUT", "INTERVALMIN", sInterMin);

        SetConfigValue("APPLICATION", "PROCESSID",  sProcessId);
        SetConfigValue("APPLICATION", "SAVEFORM",   sSaveForm);

        CenterId   = sCenterId;
        CenterName = sCenterName;
        CenterCd   = String(StrToInt(CenterId.SubString(2, 2)));

        g_AppCfg.itsdb.sProvider   = sDbProvider;
        g_AppCfg.itsdb.sUserName   = sDbUser;
        g_AppCfg.itsdb.sServerName = sDbSource;
        g_AppCfg.itsdb.sPassword   = sDbPasswd;
        g_AppCfg.sProcessId        = sProcessId;

        Application->MessageBox(L"환경설정 정보를 정상적으로 저장하였습니다.\r\다음 프로그램 실행 부터 반영됩니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
    } catch(...) {
    }

    //Close();
}
//---------------------------------------------------------------------------

void __fastcall TCFG0000M::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    CFG0000M = NULL;
    Action = caFree;
}
//---------------------------------------------------------------------------

String __fastcall TCFG0000M::GetConfigValue(String sSection, String sIdent, String sDefVal)
{
    String    sResult = sDefVal;
    TIniFile *pIniFile  = NULL;

    String sCfgFile = ExtractFilePath(Application->ExeName) + "\\Cfg\\ITS_OP.ini";

    try
    {
        pIniFile = new TIniFile(sCfgFile);
        sResult = pIniFile->ReadString(sSection, sIdent, sDefVal);
    }
    __finally
    {
        if (pIniFile) delete pIniFile;
        pIniFile = NULL;
    }
    return sResult;
}
//---------------------------------------------------------------------------

void __fastcall TCFG0000M::SetConfigValue(String sSection, String sIdent, String sSetVal)
{
    TIniFile *pIniFile  = NULL;

    String sCfgFile = ExtractFilePath(Application->ExeName) + "\\Cfg\\ITS_OP.ini";

    try
    {
        pIniFile = new TIniFile(sCfgFile);
        pIniFile->WriteString(sSection, sIdent, sSetVal);
    }
    __finally
    {
        if (pIniFile) delete pIniFile;
        pIniFile = NULL;
    }
}
//---------------------------------------------------------------------------

void __fastcall TCFG0000M::EdGisFilePropertiesButtonClick(TObject *Sender, int AButtonIndex)
{
    try {
        OpenDialog1->FileName = EdGisFile->Text.Trim();
        OpenDialog1->InitialDir = ExtractFilePath(Application->ExeName) + "\\cfg\\";
        OpenDialog1->HistoryList->Clear();
        OpenDialog1->Filter = "지도설정파일 (*.DVA)|*.DVA";
        //OpenDialog1->Options = dlgOpen->Options << ofFileMustExist;
        //OpenDialog1->Options = dlgOpen->Options >> ofAllowMultiSelect;

        if (!OpenDialog1->Execute()) return;

        EdGisFile->Text = OpenDialog1->FileName;
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TCFG0000M::BtnDbTestClick(TObject *Sender)
{
    String sDbProvider = EdDbProvider->Text.Trim();
    String sDbUser     = EdDbUser->Text.Trim();
    String sDbSource   = EdDbSource->Text.Trim();
    String sDbPasswd   = EdDbPasswd->Text.Trim();

	if (!ITSDb_Initialize())
	{
        Application->MessageBox(L"Database 자원을 시스템으로부터 얻지 못했습니다.",
                                FTitle.c_str(),
                                MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return;
	}
    ITSDb_SetInfo(sDbProvider, sDbSource, sDbUser, sDbPasswd);
    if (ITSDb_Open())
    {
        Application->MessageBox(L"Database와 연결 테스트에 성공하였습니다.", FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);
    }
    else
    {
        Application->MessageBox(L"Database와 연결 테스트에 실패하였습니다.", FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
    }
    ITSDb_Close();
    ITSDb_Finalize();
}
//---------------------------------------------------------------------------

