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

#include <vcl.h>
#pragma hdrstop

#include "AppGlobalF.h"
#include "ITSDbF.h"
#include "FRMLoginF.h"
#include "ITSUtilF.h"
#include "CDSVmsObjTypeF.h"
#include "ITS_OPLibF.h"
#include <inifiles.hpp>

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

#pragma package(smart_init)

//---------------------------------------------------------------------------
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
String           g_sBlackBox = "";
String           g_sLangDir = "";
String           g_sImageDir = "";
String           g_sVideoDir = "";

LOGININFO       *g_pLOGIN = NULL;
LOG_INFO         g_LogCfg;
TITSLog         *FDbLog = NULL;
String           g_sLang = "kr";

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

void LoadIcon(TIniFile* AIniFile, String ASection, String AItem, String& AValue)
{
    try
    {
        AValue = AIniFile->ReadString(ASection, AItem, "");
        if (AValue != "")
        {
            AValue = g_sAppDir + "Image\\" + AValue;
            if (!FileExists(AValue)) AValue = "";
        }
    }
    catch(Exception &e)
    {
    }
}
//---------------------------------------------------------------------------

bool LoadDefaultConfigInfo(String ACfgFile/*=""*/)
{
    String   sCfgFile;
    TIniFile *pIniFile = NULL;

    String sIniFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".ini");
    if (!ACfgFile.IsEmpty())
        sIniFile = ACfgFile + ".ini";

    sCfgFile = g_sCfgDir + sIniFile;
    g_AppCfg.sConfigFile = sCfgFile;

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

    g_AppCfg.bAppClose      = false;
    g_AppCfg.isLoadFromFile = false;

    pIniFile = new TIniFile(sCfgFile);

    try
    {
        g_AppCfg.sTitle       = pIniFile->ReadString("APPLICATION", "TITLE",     "교통정보시스템 통합 운영단말");
        g_AppCfg.sProcessId   = pIniFile->ReadString("APPLICATION", "PROCESSID", "OPER01");
        g_AppCfg.sLogDay      = pIniFile->ReadString("APPLICATION", "LOGDAY",    "");
        g_AppCfg.sAppPath     = pIniFile->ReadString("APPLICATION", "APP_PATH",  "");

        g_AppCfg.sSkinName    = pIniFile->ReadString("APPLICATION", "SKINNAME",    "Blue");
        g_AppCfg.bSaveForm    = pIniFile->ReadString("APPLICATION", "SAVEFORM",    "1").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.bLoginPrompt = pIniFile->ReadString("APPLICATION", "LOGINPROMPT", "1").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.sDefUseId    = pIniFile->ReadString("APPLICATION", "LASTUSER",    "");

        g_AppCfg.sLang = pIniFile->ReadString("APPLICATION", "LANGUAGE", "kr").LowerCase();
        if (g_AppCfg.sLang != "en" && g_AppCfg.sLang != "kr") g_AppCfg.sLang = "kr";
        g_sLang = g_AppCfg.sLang;

        g_AppCfg.bDebug         = pIniFile->ReadString("APPLICATION", "DEBUG",     "0").ToIntDef(0) == 1 ? true : false;
        g_AppCfg.bTermChildProg = pIniFile->ReadString("APPLICATION", "TERMCHILD", "1").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.bOnlyOneScreen = pIniFile->ReadString("APPLICATION", "ONESCREEN", "1").ToIntDef(1) == 1 ? true : false;


        g_AppCfg.itsdb.bSqlLog     = pIniFile->ReadString("ITSDB", "SQLLOG",     "0").ToIntDef(0) == 1 ? true : false;
        g_AppCfg.itsdb.sConnectStr = pIniFile->ReadString("ITSDB", "CONNECTSTR", "");
        if (g_AppCfg.itsdb.sConnectStr == "")
        {
            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");
        }


        //시설물 온도알람을 사용하지 않는경우 100도가 되기때문에 실제적으로 알람이 발생하지 않는 효과가 있음
        //즉, 온도이상알람을 원하는 경우에만 알람값을 설정하여 사용하면 됨
        g_AppCfg.Temp.AlarmValue  = pIniFile->ReadString("TEMPERATURE", "ALARMVALUE", "100").ToIntDef(100);   //45
        //시설물알람
        g_AppCfg.Alarm.Enabled    = pIniFile->ReadString("ALARM",       "ENABLED",      "0").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.Alarm.Window     = pIniFile->ReadString("ALARM",       "WINDOW",       "1").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.Alarm.TimeOut    = pIniFile->ReadString("ALARM",       "TIMEOUT",     "10").ToIntDef(10);
        //돌발알람
        g_AppCfg.Incident.Enabled = pIniFile->ReadString("INCIDENT",    "ENABLED",      "0").ToIntDef(0) == 1 ? true : false;
        g_AppCfg.Incident.Window  = pIniFile->ReadString("INCIDENT",    "WINDOW",       "1").ToIntDef(1) == 1 ? true : false;
        g_AppCfg.Incident.TimeOut = pIniFile->ReadString("INCIDENT",    "TIMEOUT",     "30").ToIntDef(30);

        if (g_AppCfg.Alarm.TimeOut    ==  0) g_AppCfg.Alarm.TimeOut    = 10;
        if (g_AppCfg.Alarm.TimeOut    >  60) g_AppCfg.Alarm.TimeOut    = 60;
        if (g_AppCfg.Incident.TimeOut ==  0) g_AppCfg.Incident.TimeOut = 30;
        if (g_AppCfg.Incident.TimeOut > 300) g_AppCfg.Incident.TimeOut = 60;

        //자동로그아웃설정
        g_AppCfg.AutoLogout.Enabled     = pIniFile->ReadString("AUTOLOGOUT", "ENABLED",      "0").ToIntDef(0) == 1 ? true : false;
        g_AppCfg.AutoLogout.LogoutExit  = pIniFile->ReadString("AUTOLOGOUT", "LOGOUTEXIT",   "0").ToIntDef(0) == 1 ? true : false;
        g_AppCfg.AutoLogout.IntervalMin = pIniFile->ReadString("AUTOLOGOUT", "INTERVALMIN", "10").ToIntDef(10);
        if (g_AppCfg.AutoLogout.IntervalMin == 0) g_AppCfg.AutoLogout.IntervalMin = 10;

        //시설물 아이콘 경로 로딩
        LoadIcon(pIniFile, "VMS", "ICON_N", g_AppCfg.vms.ICON[icon_n]);
        LoadIcon(pIniFile, "VMS", "ICON_E", g_AppCfg.vms.ICON[icon_e]);
        LoadIcon(pIniFile, "VMS", "ICON_M", g_AppCfg.vms.ICON[icon_m]);
        LoadIcon(pIniFile, "VMS", "ICON_R", g_AppCfg.vms.ICON[icon_r]);
        LoadIcon(pIniFile, "VMS", "ICON_S", g_AppCfg.vms.ICON[icon_s]);

        LoadIcon(pIniFile, "VDS", "ICON_N", g_AppCfg.vds.ICON[icon_n]);
        LoadIcon(pIniFile, "VDS", "ICON_E", g_AppCfg.vds.ICON[icon_e]);
        LoadIcon(pIniFile, "VDS", "ICON_M", g_AppCfg.vds.ICON[icon_m]);
        LoadIcon(pIniFile, "VDS", "ICON_R", g_AppCfg.vds.ICON[icon_r]);
        LoadIcon(pIniFile, "VDS", "ICON_S", g_AppCfg.vds.ICON[icon_s]);

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

        // GIS 설정정보 로딩
        g_GisInfo.mapType = pIniFile->ReadString("MAP", "MAPTYPE", "1").ToIntDef(1);
        g_GisInfo.mapUrl  = pIniFile->ReadString("MAP", "MAPURL",  "http://xdworld.vworld.kr:8080/2d/Base/service");

        if (g_GisInfo.mapType != 0 && g_GisInfo.mapType != 1) g_GisInfo.mapType = 1;    /* 1: Online, 0: Offline */
        g_GisInfo.mapType = 0;  // Offline
        if (APP_IsDirectoryExists(g_GisInfo.mapUrl.c_str()))
        {
            g_GisInfo.mapUrl = g_GisInfo.mapUrl+"\\";
            g_GisInfo.mapUrl = StringReplace(g_GisInfo.mapUrl, ":\\", "://", TReplaceFlags() << rfReplaceAll);
            g_GisInfo.mapUrl = StringReplace(g_GisInfo.mapUrl, "\\", "/", TReplaceFlags() << rfReplaceAll);
        }
        else
        {
            if (g_GisInfo.mapUrl.UpperCase().Pos("HTTP"))
            {
                g_GisInfo.mapUrl = g_GisInfo.mapUrl+"/";
            }
            else
            {
                g_GisInfo.mapUrl = "";
            }
        }

        g_nMapSource  = pIniFile->ReadInteger("MAP", "MAPSOURCE", 1);
        g_GisInfo.imagePath = g_sMapDir+"images\\";
        g_GisInfo.imagePath = StringReplace(g_GisInfo.imagePath, ":\\", "://", TReplaceFlags() << rfReplaceAll);
        g_GisInfo.imagePath = StringReplace(g_GisInfo.imagePath, "\\", "/", TReplaceFlags() << rfReplaceAll);

        g_GisInfo.sApiKey       = pIniFile->ReadString("MAP", "APIKEY",       "");
        g_GisInfo.nZoomLevel    = pIniFile->ReadString("MAP", "INITZOOM",     "11").ToIntDef(11);
        g_GisInfo.nMinZoom      = pIniFile->ReadString("MAP", "MINZOOM",      "1").ToIntDef(1);
        g_GisInfo.nMaxZoom      = pIniFile->ReadString("MAP", "MAXZOOM",      "19").ToIntDef(9);
        g_GisInfo.nFacilityZoom = pIniFile->ReadString("MAP", "FACILITYZOOM", "14").ToIntDef(14);
        g_GisInfo.dCenterX      = pIniFile->ReadString("MAP", "CENTERX",      "33.3536449").ToDouble();
        g_GisInfo.dCenterY      = pIniFile->ReadString("MAP", "CENTERY",      "126.5278103").ToDouble();
        String sLoading = pIniFile->ReadString("MAP", "LOADING", "file");
        if (sLoading == "file") g_AppCfg.isLoadFromFile = true;

        //VMS FTP
        g_AppCfg.vmsFtp.SERVER  = pIniFile->ReadString("VMS_FTP", "SERVER",  "");
        g_AppCfg.vmsFtp.PORT    = pIniFile->ReadString("VMS_FTP", "PORT",    "21").ToIntDef(21);
        g_AppCfg.vmsFtp.USER    = pIniFile->ReadString("VMS_FTP", "USER",    "");
        g_AppCfg.vmsFtp.PSWD    = pIniFile->ReadString("VMS_FTP", "PSWD",    "");
        g_AppCfg.vmsFtp.PASSIVE = pIniFile->ReadString("VMS_FTP", "PASSIVE", "0").ToIntDef(0) == 0 ? false : true;
    }
    __finally
    {
        if (pIniFile) delete pIniFile;
        pIniFile = NULL;
        WriteConfigInfo(sCfgFile, "AUTOLOGOUT", "LOGOUTEXIT", "0");
    }

    return true;
}
//---------------------------------------------------------------------------
bool CMM_InsertLoginHist(PLOGININFO pLogin, bool ALogin)
{
    String     sQry;
    bool       bResult= false;
    TADOQuery *adoQry = NULL;

    if (!pLogin) return false;

    if (ALogin)
    {
//        sQry = "INSERT INTO TB_USER_CNNC_HS ( \r\n"
        sQry = "INSERT INTO TB_USERCNNC_HS (  \r\n"
               "       LOGIN_HMS,             \r\n"
               "       USER_ID,               \r\n"
               "       LOGOUT_HMS             \r\n"
               "       )                      \r\n"
               "VALUES (                      \r\n"
               "       :p01,                  \r\n"
               "       :p02,                  \r\n"
               "       NULL                   \r\n"
               "       )                      \r\n";
    }
    else
    {
//        sQry = "UPDATE TB_USER_CNNC_HS SET                               \r\n"
        sQry = "UPDATE TB_USERCNNC_HS SET                                \r\n"
               "       LOGOUT_HMS = TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') \r\n"
               " WHERE LOGIN_HMS = :p01                                  \r\n"
               "   AND USER_ID   = :p02                                  \r\n";
    }

    try
    {
        try
        {
            adoQry = new TADOQuery(NULL);
            adoQry->Connection = ITSDb_GetConnection();

            ITSDb_GetConnection()->BeginTrans();

            adoQry->Close();
            adoQry->SQL->Text = sQry;
            adoQry->Parameters->ParamByName("p01")->Value = pLogin->sLoginTime;
            adoQry->Parameters->ParamByName("p02")->Value = pLogin->sUserId;

            int nRowCnt = adoQry->ExecSQL();

            ITSDb_GetConnection()->CommitTrans();
            bResult = nRowCnt > 1 ? true : false;
        }
        catch (Exception &exception)
        {
            ITSDb_GetConnection()->RollbackTrans();
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
        catch (...)
        {
            ITSDb_GetConnection()->RollbackTrans();
        }
    }
    __finally
    {
        if (adoQry)
        {
            adoQry->Close();
            delete adoQry;
        }
    }
    return bResult;
}
//---------------------------------------------------------------------------

bool ITSLoginProc(String sConnSystem, String sDefUser, TComponent *Owner)
{
    bool       bResult= false;
	PLOGININFO pLogin = ITSDb_GetLoginInfo();
    if (NULL == pLogin) return bResult;

    FRMLogin = new TFRMLogin(Owner);
	if (FRMLogin)
	{
        FRMLogin->EdUserID->Text = sDefUser;
        FRMLogin->ShowModal();
        pLogin->bLogin = FRMLogin->m_bLogin;

        if (pLogin->bLogin)
        {
            pLogin->sUserId        = FRMLogin->m_sUserID;
            pLogin->sUserName      = FRMLogin->m_sUserName;
            pLogin->sUserRightId   = FRMLogin->m_sUserRightID;
            pLogin->sUserRightName = FRMLogin->m_sUserRightName;
            pLogin->sConnSystem    = sConnSystem;
            pLogin->sLoginIp       = FRMLogin->GetLocalIp();
            pLogin->sLoginTime     = FRMLogin->m_sLoginTime;
        }
        else
        {
            pLogin->sUserId        = "default";
            pLogin->sUserName      = "default";
            pLogin->sUserRightId   = "1";
            pLogin->sUserRightName = "";
            pLogin->sConnSystem    = "OPR";
            pLogin->sLoginSeq      = "0";
            pLogin->sLoginIp       = "127.0.0.1";
            pLogin->sLoginTime     = Now().FormatString("yyyymmddhhnnss");
        }

        delete FRMLogin;
        FRMLogin = NULL;

        bResult  = pLogin->bLogin;
	}
	else
	{
		bResult = false;
	}

    if (bResult) CMM_InsertLoginHist(pLogin, true);

	return bResult;
}
//---------------------------------------------------------------------------

void ITSLogoutProc()
{
    if (ITSDb_IsOpen() == false) return;

	PLOGININFO  pLogin = ITSDb_GetLoginInfo();
	if (pLogin)
    {
        if (pLogin->bLogin) CMM_InsertLoginHist(pLogin, false);
        pLogin->bLogin = false;
    }
}
//---------------------------------------------------------------------------

int UserLogin()
{
    if (ITSLoginProc("OPR", g_AppCfg.sDefUseId, Application))
    {
        g_pLOGIN = ITSDb_GetLoginInfo();

        if (g_pLOGIN) WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "LASTUSER", g_pLOGIN->sUserId);
    }

    return g_pLOGIN == NULL ? 0 : 1;
}
//---------------------------------------------------------------------------

int UserLogout()
{
    if (g_pLOGIN)
        WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "LASTUSER", g_pLOGIN->sUserId);

    if (g_AppCfg.AutoLogout.LogoutExit)
        WriteConfigInfo(g_AppCfg.sConfigFile, "AUTOLOGOUT", "LOGOUTEXIT", "1");
    else
        WriteConfigInfo(g_AppCfg.sConfigFile, "AUTOLOGOUT", "LOGOUTEXIT", "0");

    ITSLogoutProc();
    g_pLOGIN = NULL;

    return 0;
}
//---------------------------------------------------------------------------

/*
 * 환경설정 정보를 저장하는 함수.
 *  arguments
 *      String : RegisterKey 또는 파일이름
 *  return
 *      bool : 실패하면 false
 */
bool WriteConfigInfo(String sCfgFile, String sTitle, String sItem, String sValue)
{
	String	 ConfigFile;
	TIniFile *pIniFile = NULL;

    ConfigFile = sCfgFile;

    try
    {
        pIniFile = new TIniFile(ConfigFile);
        if (pIniFile == NULL)
        {
            return false;
        }

        pIniFile->WriteString(sTitle, sItem, sValue);
    }
    catch(...)
    {
    }

    if (pIniFile)
    {
        pIniFile->Free();
        pIniFile = NULL;
    }

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

/*
 * 환경설정 정보를 읽어오는 함수.
 *  arguments
 *      String : RegisterKey 또는 파일이름
 *  return
 *      bool : 실패하면 false
 */
bool ReadConfigInfo(String sCfgFile, String sTitle, String sItem, String &sValue)
{
    bool     bRes;
	String   ConfigFile;
	TIniFile *pIniFile = NULL;

    bRes = false;

    ConfigFile = sCfgFile;

    try
    {
        pIniFile = new TIniFile(ConfigFile);
        if (pIniFile == NULL)
        {
            return bRes;
        }

        sValue = pIniFile->ReadString(sTitle, sItem, "");
        if (sValue != "")
        {
            bRes = true;
        }
    }
    catch(...)
    {
    }

    if (pIniFile)
    {
        pIniFile->Free();
        pIniFile = NULL;
    }

	return bRes;
}
//---------------------------------------------------------------------------


