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

#include <vcl.h>
#include "WindowMsgF.h"
#include "AppGlobalF.h"
#include "ITSUtilF.h"
#include "CDSLinkF.h"
#include "CDSIfscF.h"
#include "CDSRoadF.h"
#include "CDSRepeatCongestF.h"
#include "CDSIncidentF.h"
#include "CDSProcessF.h"
#include "CDSFacilityF.h"
#include "CDSVilgFrcsF.h"
#include "CDSDatabaseF.h"

#ifdef USE_UTIS
    #include "CDSUtisF.h"
#endif

#pragma hdrstop

#include "TThreadPollingF.h"

#pragma warning(disable:8004)
#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
    {
        FreeOnTerminate	= true;
        Priority 		= tpNormal;//tpIdle;//tpNormal

        g_AppCfg.thr.bRunning = true;

        m_lMainWinHandle = (HWND)g_AppCfg.lMainWinHandle;

        m_sDbConnString  = "";

        if (g_AppCfg.itsdb.sConnectStr == "")
        {
            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;
        }
        else
        {
            m_sDbConnString  = g_AppCfg.itsdb.sConnectStr;
        }

        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;

    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 (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:
                    if (m_pConnection->Connected == false)
                    {
                        if (DbConnect() == false)
                        {
                            POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, Msg.lParam);
                        }
                    }
                    if (IsDbOpen())
                    {
                        switch(Msg.lParam)
                        {
                        case LP_MSG_TRAFFIC:        SelTrafficAllData(Msg.lParam);      break;
                        case LP_MSG_FACILITY_STTS:  SelFacilityStatusData(Msg.lParam);  break;
                        case LP_MSG_PROCESS_STTS:   SelProcessStatusData(Msg.lParam);   break;
                        case LP_MSG_INCIDENT:       SelIncidentData(Msg.lParam);        break;
                        case LP_MSG_DATABASE_STTS:  SelDatabaseSttsData(Msg.lParam);    break;

                        case LP_MSG_05: SelTrafficUtisRunData(Msg.lParam);     break;
                        case LP_MSG_14: SelFacilityData(Msg.lParam);           break;
                        case LP_MSG_09: SelProcessData(Msg.lParam);            break;
                        case LP_MSG_16: SelBlackBoxEventData(Msg.lParam);      break;
                        case LP_MSG_WEATHER: SelVilgFrcsData(Msg.lParam);      break;
                        }
                    }
                    break;
                }
            }
            catch(...)
            {
                //nRes = -999;
            }
        }
        if (nRes == -999) break;
    }
//    ::CoUninitialize();
}
//---------------------------------------------------------------------------

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

    //링크소통정보(전체)
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);

    bRes = ItsLinkManager->LoadTraffic(m_pConnection);
    bRes = ItsIfscManager->LoadTraffic(m_pConnection);
    bRes = ItsRoadManager->LoadTraffic(m_pConnection);
    bRes = ItsRepeatCongestManager->LoadFromDb(m_pConnection);
    bRes = ItsLinkManager->LoadClctSystStts(m_pConnection);

    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //UTIS 운영상태
#ifdef USE_UTIS
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsUtisManager->LoadUtisStatusFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }
#else
    bRes = true;
#endif

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

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

    //데이터베이스 상태
    bRes = ItsDatabaseManager->LoadFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //시설물 상태정보
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsFacilityManager->LoadFacilityStatusFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        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 == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

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

    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //시설물정보 재로딩
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsFacilityManager->LoadFromDb(m_pConnection);
    if (bRes == false)
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
        return false;
    }
    bRes = ItsFacilityManager->LoadFacilityStatusFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //프로세스정보 재로딩
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsProcessManager->LoadFromDb(m_pConnection);
    if (bRes == false)
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
        return false;
    }
    bRes = ItsProcessManager->LoadProcessStatusFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //블랙박스이벤트 재로딩
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsEventManager->LoadFromDb(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

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

    //기상정보 조회
    POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_START, LParam);
    bRes = ItsVilgFrcsManager->LoadVilgFrcsInfo(m_pConnection);
    if (bRes == true)
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_OK,    LParam);
    else
    {
        m_pConnection->Close();
        POST_MSG(m_lMainWinHandle, WM_THREAD, WP_DB_SELECT_ERROR, LParam);
    }

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

