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

#include <vcl.h>
#include "WindowMsgF.h"
#include "AppGlobalF.h"
#include "ITSUtilF.h"
#include "CDSIncidentF.h"
#include "CDSVmsIfscF.h"
#include "CDSIfsc_VMSF.h"
#include "CDSProcessF.h"
#pragma hdrstop

#include "TThreadPollingF.h"

#pragma package(smart_init)
//---------------------------------------------------------------------------

//   Important: Methods and properties of objects in VCL can only be
//   used in a method called using Synchronize, for example:
//
//      Synchronize(&UpdateCaption);
//
//   where UpdateCaption could look like:
//
//      void __fastcall TThreadPolling::UpdateCaption()
//      {
//        Form1->Caption = "Updated in a thread";
//      }
//---------------------------------------------------------------------------

__fastcall TThreadPolling::TThreadPolling(bool CreateSuspended)
    : TThread(CreateSuspended)
{
    ::CoInitialize(NULL);

    try
    {
//if (g_AppCfg.bDebug) ITSUtil_Trace("Start");

        FreeOnTerminate	= true;
        Priority 		= tpNormal;//tpIdle;//tpNormal

        g_AppCfg.thr.bRunning = true;

        m_lMainWinHandle = (HWND)g_AppCfg.lMainWinHandle;

        m_sDbConnString  = "";
        m_sDbConnString += "Provider="     + g_AppCfg.itsdb.sProvider;
        m_sDbConnString += ";Password="    + g_AppCfg.itsdb.sPassword;
        m_sDbConnString += ";Persist Security Info=True";
        m_sDbConnString += ";User ID="     + g_AppCfg.itsdb.sUserName;
        m_sDbConnString += ";Data Source=" + g_AppCfg.itsdb.sServerName;

        m_pConnection      = NULL;
        m_pConnection	   = new TADOConnection(NULL);
    }
    catch(...)
    {
        Terminate();
    }
}
//---------------------------------------------------------------------------
__fastcall TThreadPolling::~TThreadPolling()
{
    if (m_pConnection)
    {
    	if (m_pConnection->Connected == true)
        {
            m_pConnection->Close();
        }
        delete m_pConnection;
        m_pConnection = NULL;
    }
//    ::CoUninitialize();
}
//---------------------------------------------------------------------------
/*
 * 데이터베이스 연결
 *  arguments
 *
 *  return
 *
 */
bool __fastcall TThreadPolling::DbConnect()
{
    ::CoInitialize(NULL);
	try
    {
        m_pConnection->ConnectionString	= m_sDbConnString;
        m_pConnection->KeepConnection	= true;
        m_pConnection->LoginPrompt		= false;
        m_pConnection->Open();
    }
    catch(EDatabaseError &E)
    {
        return false;
    }
	catch (Exception &e)
	{
        return false;
	}
    catch (...)
    {
        return false;
    }

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

void __fastcall TThreadPolling::Execute()
{
    ::CoInitialize(NULL);

    NameThreadForDebugging("PollingThread");

    MSG Msg;
    int nRes;

//if (g_AppCfg.bDebug) ITSUtil_Trace("Execute");

    while (!Terminated)
    {
        if (DbConnect())
        {
            break;
        }
        if (g_AppCfg.bAppClose)
        {
            return;
        }
        Sleep(1000);
    }

    while(!Terminated)
    {
        if (GetMessage(&Msg, NULL, 0, 0) == 0) {
            Terminate();
        }
        else {
            nRes = 0;
            try
            {
                if (Msg.message == WM_QUIT)
                {
                    nRes = -999;
                    break;
                }
#if 0
                if (Msg.wParam == WM_QUIT)
                {
                    nRes = -999;
                    break;
                }
#endif
                if (Msg.message != WM_THREAD) continue;

                if (!IsDbOpen())
                {
                    DbConnect();
                }

                m_lMainWinHandle = (HWND)g_AppCfg.lMainWinHandle;
                switch (Msg.wParam)
                {
                case WP_PING:
                    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_PING, WP_PING);
                    break;
                case WP_PARAM_TRAFFIC:
                    switch(Msg.lParam)
                    {
                    case LP_MSG_PROCESS_STTS:  SelProcessStatusData(Msg.lParam);   break;
                    case LP_MSG_FACILITY_STTS: SelVmsStatusData(Msg.lParam);       break;
                    case LP_MSG_VMS_DSPLMSG:   SelVmsMsg(Msg.lParam);              break;
                    case LP_MSG_TRAFFIC:       SelIfscTrafficData(Msg.lParam);     break;
                    case LP_MSG_INCIDENT:      SelIncidentData(Msg.lParam);        break;
                    }
                    break;
                }
            }
            catch(...)
            {
                //nRes = -999;
            }
        }
        if (nRes == -999) break;
    }
//    ::CoUninitialize();
}
//---------------------------------------------------------------------------

bool __fastcall TThreadPolling::SelIfscTrafficData(LPARAM LParam)
{
    bool bRes = false;

    //서비스링크 소통정보(레벨2)
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = IfscManager->LoadTraffic(m_pConnection);
    bRes = VmsIfscManager->LoadTraffic(m_pConnection);
    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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

bool __fastcall TThreadPolling::SelVmsIfscTrafficData(LPARAM LParam)
{
    bool bRes = false;

    //VMS정보제공구간소통정보
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = VmsIfscManager->LoadTraffic(m_pConnection);
    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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

bool __fastcall TThreadPolling::SelVmsStatusData(LPARAM LParam)
{
    bool bRes = false;

    //시설물(VMS) 상태정보
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = VmsCtlrManager->LoadStatusFromDb(m_pConnection);
    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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

bool __fastcall TThreadPolling::SelProcessStatusData(LPARAM LParam)
{
    bool bRes = false;

    //프로세스 상태정보
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsProcessManager->LoadProcessStatusFromDb(m_pConnection);
    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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

bool __fastcall TThreadPolling::SelIncidentData(LPARAM LParam)
{
    bool bRes = false;

    if (ItsIncidentManager)
    {
        //돌발발생정보
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
#if 0
        bRes = ItsIncidentManager->LoadFromDb(m_pConnection);
#endif
        //bRes = ItsIncidentManager->LoadFromAutoIncident(m_pConnection);
    }
    else
    {
        bRes = true;
    }

    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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

bool __fastcall TThreadPolling::SelVmsMsg(LPARAM LParam)
{
    bool bRes = false;

    //VMS Message 재로딩
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = VmsCtlrManager->LoadVmsMsg(m_pConnection);
    if (bRes)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);

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


