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

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

//---------------------------------------------------------------------------
USEFORM("MAIN\FrmCctvOprMainF.cpp", FrmCctvOprMain);
USEFORM("PLUGIN\CTV0100M\CTV0100MF.cpp", CTV0100M);
USEFORM("..\COMMON\FRAME\FRAME_CctvListF.cpp", FRAMECctvList); /* TFrame: File Type */
USEFORM("PLUGIN\CTVM100M\CTVM100MF.cpp", CTVM100M);
USEFORM("..\COMMON\FRAME\FRAME_OpenMapF.cpp", FRAMEOpenMap); /* TFrame: File Type */
USEFORM("PLUGIN\CTV0100M\CTV0101MF.cpp", CTV0101M);
USEFORM("PLUGIN\99.LOGIN\FRMLoginF.cpp", FRMLogin);
USEFORM("PLUGIN\00.FRAME\FRAME_CctvStateListF.cpp", FRAMECctvStateList); /* TFrame: File Type */
USEFORM("PLUGIN\99.LOGIN\FRMPswdChngeF.cpp", FRMPswdChnge);
USEFORM("MAIN\FrmInitializeF.cpp", FrmInitialize);
USEFORM("MAIN\FrmResourceF.cpp", FrmLang);
USEFORM("PLUGIN\CTV0500M\CTV0500MF.cpp", CTV0500M);
USEFORM("PLUGIN\CTV0300M\CTV0300MF.cpp", CTV0300M);
//---------------------------------------------------------------------------
WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
    int nLoginRes;

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


    String sLoginId = "ADMIN";
    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_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_sMapDir.c_str());
    String sTempDir = g_sLogDir + "Db\\";
    ForceDirectories(sTempDir.c_str());

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

    HANDLE hMutex;
	try
	{
        String sLockFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".lock");
        String sProgMutexNm = "HANTE_POHANG_" + 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"CCTV 운영단말 프로그램이 이미 실행중입니다.\r\n작업관리자의 프로세스 목록에서 프로그램을 종료후 실행해 주십시오.",
                                        L"프로그램 시작 오류!!!",
                                        MB_OK|MB_ICONERROR);
            }
            else
            {
                Application->MessageBox(L"The CCTV 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;
    }

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

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

    LangTrans = new TLangTrans("CctvOprMain", 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        = sLoginId;
        g_pLOGIN->sUserName      = "default";
        g_pLOGIN->sUserRightId   = "1";
        g_pLOGIN->sUserRightName = "";
        g_pLOGIN->sConnSystem    = "OPR";
        g_pLOGIN->sLoginSeq      = "0";
        g_pLOGIN->sLoginIp       = "127.0.0.1";
        g_pLOGIN->sLoginTime     = Now().FormatString("yyyymmddhhnnss");
    }

    try
    {
        ReportMemoryLeaksOnShutdown = true;
        Application->Initialize();
        Application->MainFormOnTaskBar = true;
        Application->Title = g_AppCfg.sTitle;
        Application->Title = "CCTV 운영관리";
         Application->CreateForm(__classid(TFrmCctvOprMain), &FrmCctvOprMain);
         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;
}
//---------------------------------------------------------------------------

