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

#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
#include <cxFormats.hpp>
//---------------------------------------------------------------------------
#include "AppGlobalF.h"
#include "ITSDbF.h"
#include "ITSLangTransF.h"

//---------------------------------------------------------------------------
USEFORM("..\COMMON\FRAME\FRAME_VmsListF.cpp", FRAMEVmsList); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM500M\VMSM510MF.cpp", VMSM510M);
USEFORM("PLUGIN\VMS0100M\VMS0100MF.cpp", VMS0100M);
USEFORM("PLUGIN\COMMON\VMSWBACKF.cpp", VMSWBACK);
USEFORM("PLUGIN\COMMON\VMSBACKMF.cpp", VMSBACKM);
USEFORM("PLUGIN\VMSM500M\VMSM500MF.cpp", VMSM500M);
USEFORM("PLUGIN\VMSM100M\VMSM100MF.cpp", VMSM100M);
USEFORM("PLUGIN\VMS0200M\VMS0200MF.cpp", VMS0200M);
USEFORM("PLUGIN\COMMON\VMSWCAM0F.cpp", VMSWCAM0);
USEFORM("MAIN\FrmVmsOprMainF.cpp", FrmVmsOprMain);
USEFORM("PLUGIN\VMSM900M\VMSM900MF.cpp", VMSM900M);
USEFORM("PLUGIN\COMMON\VMSVIEWMF.cpp", VMSVIEWM);
USEFORM("PLUGIN\VMSM200M\VMSM200MF.cpp", VMSM200M);
USEFORM("PLUGIN\VMSM410M\VMSM410MF.cpp", VMSM410M);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsStateF.cpp", FRAMEVmsState); /* TFrame: File Type */
USEFORM("PLUGIN\COMMON\VMSMODL0F.cpp", VMSMODL0);
USEFORM("PLUGIN\99.LOGIN\FRMLoginF.cpp", FRMLogin);
USEFORM("PLUGIN\VMSM600M\VMSM630MF.cpp", VMSM630M);
USEFORM("PLUGIN\VMSM500M\VMSM520MF.cpp", VMSM520M);
USEFORM("PLUGIN\VMSM210M\VMSM210MF.cpp", VMSM210M);
USEFORM("PLUGIN\VMS0010M\VMS0010MF.cpp", VMS0010M);
USEFORM("PLUGIN\VMS0000M\FrmVmsMsgF.cpp", FrmVmsMsg);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsMsgListF.cpp", FRAMEVmsMsgList); /* TFrame: File Type */
USEFORM("PLUGIN\VMS0000M\VMS0000MF.cpp", VMS0000M);
USEFORM("PLUGIN\VMS0000M\FrmIcsCamF.cpp", FrmIcsCam);
USEFORM("PLUGIN\99.LOGIN\FRMPswdChngeF.cpp", FRMPswdChnge);
USEFORM("PLUGIN\VMSM400M\VMSM400MF.cpp", VMSM400M);
USEFORM("PLUGIN\VMSM800M\VMSM800MF.cpp", VMSM800M);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsSchListF.cpp", FRAMEVmsSchList); /* TFrame: File Type */
USEFORM("PLUGIN\COMMON\VMSEDT0MF.cpp", VMSEDT0M);
USEFORM("PLUGIN\VMS0600M\VMS0600MF.cpp", VMS0600M);
USEFORM("PLUGIN\VMS0000M\VMS00MAPF.cpp", VMS00MAP);
USEFORM("PLUGIN\VMS0500M\VMS0500MF.cpp", VMS0500M);
USEFORM("PLUGIN\COMMON\VMSSEL0MF.cpp", VMSSEL0M);
USEFORM("PLUGIN\00.FRAME\FRAME_FacilityStatusListF.cpp", FRAMEFacilityStatusList); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM500M\VMSM530MF.cpp", VMSM530M);
USEFORM("PLUGIN\VMS0300M\VMS0300MF.cpp", VMS0300M);
USEFORM("PLUGIN\VMS0200M\VMS0201MF.cpp", VMS0201M);
USEFORM("PLUGIN\VMSM600M\VMSM600MF.cpp", VMSM600M);
USEFORM("PLUGIN\VMS0000M\FrmVmsCamF.cpp", FrmVmsCam);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsStateListF.cpp", FRAMEVmsStateList); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM700M\VMSM700MF.cpp", VMSM700M);
USEFORM("PLUGIN\VMSM600M\VMSM610MF.cpp", VMSM610M);
USEFORM("PLUGIN\COMMON\VMSFORM0F.cpp", VMSFORM0);
USEFORM("PLUGIN\VMSM420M\VMSM420MF.cpp", VMSM420M);
USEFORM("..\COMMON\FRAME\FRAME_OpenMapF.cpp", FRAMEOpenMap); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM430M\VMSM430MF.cpp", VMSM430M);
USEFORM("MAIN\FrmResourceF.cpp", FrmLang);
USEFORM("PLUGIN\VMSM500M\VMSM550MF.cpp", VMSM550M);
USEFORM("PLUGIN\VMSM600M\VMSM650MF.cpp", VMSM650M);
USEFORM("PLUGIN\00.FRAME\FRAME_GoogleMapF.cpp", FRAMEGoogleMap); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM600M\VMSM620MF.cpp", VMSM620M);
USEFORM("PLUGIN\VMSM500M\VMSM540MF.cpp", VMSM540M);
USEFORM("PLUGIN\VMSM600M\VMSM640MF.cpp", VMSM640M);
USEFORM("MAIN\FrmInitializeF.cpp", FrmInitialize);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsIfscListF.cpp", FRAMEVmsIfscList); /* TFrame: File Type */
USEFORM("PLUGIN\VMSM600M\VMSM660MF.cpp", VMSM660M);
USEFORM("PLUGIN\00.FRAME\FRAME_VmsStatusF.cpp", FRAME_VmsStatus); /* TFrame: File Type */
//---------------------------------------------------------------------------
WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
    int nLoginRes;

    DateSeparator = '-';
    TimeSeparator = ':';
    ShortDateFormat ="yyyy-MM-dd";
    ShortTimeFormat = "hh:nn:ss";
    LongTimeFormat  = "hh:nn:ss";


    String sLoginId = "PATMS";
    bool bLogin = true;
    int nArgs = ParamCount();
    if (nArgs >= 1)
    {
        sLoginId = ParamStr(1);
        //ShowMessage(sLoginId);
        bLogin = false;
    }

    int nRes;
    g_nPid     = (int)GetCurrentProcessId();
    g_sAppDir  = ExtractFilePath(Application->ExeName);
    g_sAppName = ChangeFileExt(ExtractFileName(Application->ExeName), "");
    g_sCfgDir  = g_sAppDir + "Cfg\\";
    g_sLogDir  = g_sAppDir + "Log\\";
    g_sTempDir = g_sAppDir + "Temp\\";
    g_sFormsDir = g_sCfgDir + "Forms\\";
    g_sImageDir = g_sAppDir + "Image\\";
    g_sVideoDir = g_sAppDir + "Video\\";
    g_sMapDir   = g_sAppDir + "MAPDATA\\";

    ForceDirectories(g_sCfgDir.c_str());
    ForceDirectories(g_sLogDir.c_str());
    ForceDirectories(g_sTempDir.c_str());
    ForceDirectories(g_sFormsDir.c_str());
    ForceDirectories(g_sImageDir.c_str());
    ForceDirectories(g_sVideoDir.c_str());
    ForceDirectories(g_sMapDir.c_str());
    String sTempDir = g_sLogDir + "Db\\";
    ForceDirectories(sTempDir.c_str());

    String sAppDir = ExtractFilePath(Application->ExeName);
    ChDir(sAppDir); 

    /*
    *  시스템 운영환경을 ini 파일에서 읽어 온다.
    */
    LoadDefaultConfigInfo("ITS_OP");

    HANDLE hMutex;
	try
	{
        String sLockFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".lock");
        String sProgMutexNm = "HANTE_PTATMS_" + sLockFile;
        if ((hMutex=OpenMutex(MUTEX_ALL_ACCESS, false, sProgMutexNm.c_str()))==NULL)
            hMutex = CreateMutex(NULL, true, sProgMutexNm.c_str());
        else 
        {
            if (g_AppCfg.sLang == "kr")
            {
                Application->MessageBox(L"VMS 운영단말 프로그램이 이미 실행중입니다.\r\n작업관리자의 프로세스 목록에서 프로그램을 종료후 실행해 주십시오.",
                                        L"프로그램 시작 오류!!!",
                                        MB_OK|MB_ICONERROR);
            }
            else
            {
                Application->MessageBox(L"The VMS operating terminal program is already running.\r\nPlease exit the program from the process list of Task Manager and execute it.",
                                        L"Program Start Error!!!",
                                        MB_OK|MB_ICONERROR);
            }
            return 0;
        }
    }
    catch (Exception &exception)
    {
        Application->ShowException(&exception);
        return 0;
    }

    g_sLangDir = g_sAppDir + "Lang\\";
    g_sLangDir = g_sLangDir + g_AppCfg.sLang + "\\";
    ForceDirectories(g_sLangDir.c_str());

    LangTrans = new TLangTrans("VmsOprMain", g_AppCfg.sLang, g_sLangDir, true);

    //CommLog = new TCommLog(g_sLogDir, g_sAppName, g_AppCfg.sLogDay);
    ITSLog = new TITSLog(g_sLogDir, g_sAppName, g_AppCfg.sLogDay);
    ITSLog->FLogCfg = g_LogCfg;
    LOGINFO("Program start....");

	if (!ITSDb_Initialize())
	{
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"Database 자원을 시스템으로부터 얻지 못했습니다.\r\n\r\n프로그램을 종료합니다.",
                                    L"프로그램 시작 오류!!!",
                                    MB_OK|MB_ICONERROR);
        }
        else
        {
            Application->MessageBox(L"Database resource could not be obtained from the system.\r\n\r\nExit the program.",
                                    L"Program Start Error!!!",
                                    MB_OK|MB_ICONERROR);
        }
        goto prog_exit;
	}
    ITSDb_SetInfo(g_AppCfg.itsdb.sProvider, g_AppCfg.itsdb.sServerName, g_AppCfg.itsdb.sUserName, g_AppCfg.itsdb.sPassword);

    g_AppCfg.bLoginPrompt = bLogin;
    if (g_AppCfg.bLoginPrompt)
    {
        /*
        *  로그인 처리(라이브러리 로딩 실패시에만 프로그램을 종료하자-일단...)
        */
        g_AppCfg.sSkinName = "Blue";

        nLoginRes = UserLogin();
        if (nLoginRes <= 0)
        {
            goto prog_exit;
        }
    }
    else
    {
        if (!ITSDb_Open())
        {
            if (g_AppCfg.sLang == "kr")
            {
                Application->MessageBox(L"데이터베이스 접속에 실패하였습니다.\r\n\r\n프로그램을 종료합니다.",
                                        L"프로그램 시작 오류!!!",
                                        MB_OK|MB_ICONERROR);
            }
            else
            {
                Application->MessageBox(L"Database connection failed.\r\n\r\nExit the program.",
                                        L"Program Start Error!!!",
                                        MB_OK|MB_ICONERROR);
            }
            goto prog_exit;
        }
        g_pLOGIN = ITSDb_GetLoginInfo();
        g_pLOGIN->bLogin         = true;
        g_pLOGIN->sUserId        = "PATMS";//sLoginId; 라이브러리함수에서 ADMIN으로 변경됨
        g_pLOGIN->sUserName      = "default";
        g_pLOGIN->sUserRightId   = "SYS1";
        g_pLOGIN->sUserRightName = "SYS1";
        g_pLOGIN->sConnSystem    = "VMM";
        g_pLOGIN->sLoginSeq      = "0";
        g_pLOGIN->sLoginIp       = "127.0.0.1";
        g_pLOGIN->sLoginTime     = Now().FormatString("yyyymmddhhnnss");

        CMM_InsertLoginHist(g_pLOGIN, true);
    }

    try
    {
        ReportMemoryLeaksOnShutdown = true;
        Application->Initialize();
        Application->MainFormOnTaskBar = true;
        Application->Title = g_AppCfg.sTitle;
        Application->Title = "VMS 운영관리";
         Application->CreateForm(__classid(TFrmVmsOprMain), &FrmVmsOprMain);
         Application->CreateForm(__classid(TFrmLang), &FrmLang);
         Application->Run();
    }
    catch (Exception &exception)
    {
         Application->ShowException(&exception);
    }
    catch (...)
    {
         try
         {
             throw Exception("");
         }
         catch (Exception &exception)
         {
             Application->ShowException(&exception);
         }
    }

prog_exit:
    try
    {
        ITSDb_Finalize();
        
        ReleaseMutex(hMutex);
        CloseHandle(hMutex);
        hMutex = NULL;
        LOGINFO("Program end....");
    }
    catch(...)
    {
    }
    
    return 0;
}
//---------------------------------------------------------------------------

