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

#include <vcl.h>
#include "WindowMsgF.h"
#include "CDSCodeF.h"
#include "CDSTrafficGradeF.h"
#include "CDSLayerF.h"
#include "CDSNodeF.h"
#include "CDSLinkF.h"
#include "CDSIfscF.h"
#include "CDSRoadF.h"
#include "CDSFacilityF.h"
#include "CDSProcessF.h"
#include "CDSIncidentF.h"
#include "CDSRepeatCongestF.h"
#include "CDSPrltCtlrF.h"
#include "CDSUtisF.h"
#include "CDSCompanyF.h"
#include "CDSColSysF.h"
#include "CDSVilgFrcsF.h"
#include "CDSDatabaseF.h"
#include "ITSLangTransF.h"
#pragma hdrstop

#include "FrmInitializeF.h"
#include "FrmMainF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxProgressBar"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinsCore"
#pragma link "IdAntiFreeze"
#pragma link "IdAntiFreezeBase"
#pragma link "IdBaseComponent"
#pragma link "IdComponent"
#pragma link "IdExplicitTLSClientServerBase"
#pragma link "IdFTP"
#pragma link "IdTCPClient"
#pragma link "IdTCPConnection"
#pragma resource "*.dfm"

//TFrmInitialize *FrmInitialize = NULL;
//---------------------------------------------------------------------------
__fastcall TFrmInitialize::TFrmInitialize(TComponent* Owner)
    : TForm(Owner)
{
    //ADOQry->Connection = ITSDb_GetConnection();
    LangTrans->Translate(this, ITSDb_GetConnection());
}
//---------------------------------------------------------------------------

void __fastcall TFrmInitialize::FormShow(TObject *Sender)
{
    Refresh();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmInitialize::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;

    Application->ProcessMessages();
    cxProgressBar1->Properties->Max = 150;

    try
    {
        Application->ProcessMessages();
        cxProgressBar1->Position = 5;
        Application->ProcessMessages();
        if (!ItsLayerManager)
        {
            ItsLayerManager = new TItsLayerManager();
            ItsLayerManager->LoadFromDb();
        }

        cxProgressBar1->Position = 10;
        LblStatus->Caption = cxLabel1->Caption;//"코드정보 로딩...";
        Application->ProcessMessages();
        if (!ItsCodeManager)
        {
            ItsCodeManager = new TItsCodeManager();
            ItsCodeManager->LoadFromDb();
        }
        if (!ItsColSysManager)
        {
            ItsColSysManager = new TItsColSysManager();
            ItsColSysManager->LoadFromDb();
        }

        cxProgressBar1->Position = 20;
        LblStatus->Caption = cxLabel2->Caption;
        Application->ProcessMessages();
        if (!ItsTrafficGradeManager)
        {
            ItsTrafficGradeManager = new TItsTrafficGradeManager();
            ItsTrafficGradeManager->LoadFromDb();
        }

        cxProgressBar1->Position = 25;
        LblStatus->Caption = cxLabel3->Caption;
        Application->ProcessMessages();
        if (!ItsVilgFrcsManager)
        {
            ItsVilgFrcsManager = new TItsVilgFrcsManager();
            ItsVilgFrcsManager->LoadFromDb();
            FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_WEATHER);
        }

        cxProgressBar1->Position = 30;
        LblStatus->Caption = cxLabel4->Caption;
        Application->ProcessMessages();
        if (!ItsNodeManager)
        {
            ItsNodeManager = new TItsNodeManager();
            ItsNodeManager->LoadFromDb();
        }

        cxProgressBar1->Position = 40;
        LblStatus->Caption = cxLabel5->Caption;


        //레벨1
        Application->ProcessMessages();
        if (!ItsLinkManager)
        {
            ItsLinkManager = new TItsLinkManager();
            ItsLinkManager->LoadFromDb();
        }

        //레벨2
        cxProgressBar1->Position = 50;
        LblStatus->Caption = cxLabel6->Caption;
        Application->ProcessMessages();
        if (!ItsIfscManager)
        {
            ItsIfscManager = new TItsIfscManager();
            ItsIfscManager->LoadFromDb();
        }

        //레벨3
        cxProgressBar1->Position = 60;
        LblStatus->Caption = cxLabel7->Caption;
        Application->ProcessMessages();
        if (!ItsRoadManager)
        {
            ItsRoadManager = new TItsRoadManager();
            ItsRoadManager->LoadFromDb();
        }

        cxProgressBar1->Position = 70;
        LblStatus->Caption = cxLabel8->Caption;
        Application->ProcessMessages();
        if (!ItsRepeatCongestManager)
        {
            ItsRepeatCongestManager = new TItsRepeatCongestManager();
        }
        FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_TRAFFIC);   //1,2,3레벨 및 반복정체 구간 소통정보 조회

        cxProgressBar1->Position = 110;

#if 0
        LblStatus->Caption = cxLabel12->Caption;
        Application->ProcessMessages();
        if (!ItsUtisManager)
        {
            ItsUtisManager = new TItsUtisManager();
            ItsUtisManager->SetCenterId(CenterId);
            ItsUtisManager->LoadFromDb();
            FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_05);
        }
#endif

        cxProgressBar1->Position = 110;
        LblStatus->Caption = cxLabel13->Caption;
        Application->ProcessMessages();
        if (!ItsFacilityManager)
        {
            ItsFacilityManager = new TItsFacilityManager();
            ItsFacilityManager->SetCenterId(CenterId);
            ItsFacilityManager->LoadFromDb();
        }
        FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_FACILITY_STTS);

        cxProgressBar1->Position = 120;
        LblStatus->Caption = cxLabel14->Caption;//"프로세스정보 로딩...";
        Application->ProcessMessages();
        if (!ItsProcessManager)
        {
            ItsProcessManager = new TItsProcessManager();
            ItsProcessManager->LoadFromDb();
        }
        FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_PROCESS_STTS);

        cxProgressBar1->Position = 130;
        LblStatus->Caption = cxLabel15->Caption;
        Application->ProcessMessages();
        if (!ItsIncidentManager)
        {
            ItsIncidentManager = new TItsIncidentManager();
        }
        FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_INCIDENT);

        if (!ItsCompanyManager)
        {
            ItsCompanyManager = new TItsCompanyManager();
        }

        if (!ItsDatabaseManager)
        {
            ItsDatabaseManager = new TItsDatabaseManager();
        }
        FrmMain->PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_DATABASE_STTS);
#if 0
        if (!ItsEventManager)
        {
            ItsEventManager = new TItsEventManager();
            ItsEventManager->LoadFromDb();
        }
#endif
    }
    catch(...)
    {
    }

    UploadVmsVideoFiles();

    Close();
}
//---------------------------------------------------------------------------
void __fastcall TFrmInitialize::FormClose(TObject *Sender, TCloseAction &Action)
{
    Action = caFree;
}
//---------------------------------------------------------------------------
bool __fastcall TFrmInitialize::VmsFtpConnect()
{
    if (g_AppCfg.vmsFtp.SERVER == "") return false;

    IdFtp->Host     = g_AppCfg.vmsFtp.SERVER;
    IdFtp->Port     = g_AppCfg.vmsFtp.PORT;
    IdFtp->Username = g_AppCfg.vmsFtp.USER;
    IdFtp->Password = g_AppCfg.vmsFtp.PSWD;
    IdFtp->Passive  = g_AppCfg.vmsFtp.PASSIVE;

    String sErrMsg;
    bool   bConnect = false;

    try
    {
        IdFtp->Connect();
        IdFtp->ChangeDir("VIDEO");
        IdFtp->IOHandler->DefStringEncoding = TIdTextEncoding::UTF8;//IndyTextEncoding(949);
        bConnect = true;

        IdFtp->TransferType = ftBinary;
    }
    catch (EIdSocketError &exSock)
    {
        sErrMsg = exSock.Message;
        sErrMsg = StringReplace(sErrMsg, "\r\n", " ", TReplaceFlags() << rfReplaceAll);
        //Application->MessageBox(sErrMsg.c_str(), FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    catch (Exception &e)
    {
        sErrMsg = e.Message;
        sErrMsg = StringReplace(sErrMsg, "\r\n", " ", TReplaceFlags() << rfReplaceAll);
        //Application->MessageBox(sErrMsg.c_str(), FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    return bConnect;
}
//---------------------------------------------------------------------------
bool __fastcall TFrmInitialize::VmsFtpFileDownload(String AOrgFile, String ADstFile)
{
    String sErrMsg;
    try
    {
        IdFtp->TransferType = ftBinary;
        IdFtp->Get(AOrgFile, ADstFile, false);
    }
    catch (EIdSocketError &exSock)
    {
        sErrMsg = exSock.Message;
        sErrMsg = StringReplace(sErrMsg, "\r\n", " ", TReplaceFlags() << rfReplaceAll);
        //Application->MessageBox(sErrMsg.c_str(), FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    catch (Exception &e)
    {
        sErrMsg = e.Message;
        sErrMsg = StringReplace(sErrMsg, "\r\n", " ", TReplaceFlags() << rfReplaceAll);
        //Application->MessageBox(sErrMsg.c_str(), FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
    }
    return true;
}
//---------------------------------------------------------------------------
void __fastcall TFrmInitialize::VmsFtpDisconnect()
{
    if (IdFtp->Connected())
    {
        IdFtp->Abort();
        IdFtp->Quit();
        IdFtp->Disconnect();
    }
}
//---------------------------------------------------------------------------
bool __fastcall TFrmInitialize::UploadVmsVideoFiles()
{
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT SYMB_LIB_NMBR, SYMB_FILE_NM          \r\n"
           "  FROM TB_VMS_SYMB_LIB                      \r\n"
           " WHERE SYMB_LIB_NMBR BETWEEN 5000 AND 5999  \r\n"
           "   AND SYMB_TYPE = 'SBT3'                   \r\n"
           "   AND DEL_YN = 'N'                         \r\n";

    ForceDirectories(g_sVideoDir.c_str());

    if (!VmsFtpConnect()) return false;

    bool bRes = false;
    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLOpen(pADO);

            for( ; !pADO->Eof; pADO->Next())
            {
                String SYMB_FILE_NM = pADO->FieldByName("SYMB_FILE_NM")->AsString;
                String strmFileName = g_sVideoDir + SYMB_FILE_NM;
                if (!FileExists(strmFileName))
                {
                    VmsFtpFileDownload(SYMB_FILE_NM, strmFileName);
                }
            }
            bRes = true;
        }
        catch(EDatabaseError &E)
        {
            DBERRORMSG("TFrmInitialize::UploadVmsVideoFiles", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORMSG("TFrmInitialize::UploadVmsVideoFiles", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        VmsFtpDisconnect();
    }
    return bRes;
}
//---------------------------------------------------------------------------

