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

#pragma hdrstop

#include "CDSRepeatCongestF.h"
#include "ITS_OPLibF.h"

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

#pragma package(smart_init)

TItsRepeatCongest::TItsRepeatCongest()
{
}
//---------------------------------------------------------------------------
TItsRepeatCongest::~TItsRepeatCongest()
{
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
TItsRepeatCongestManager *ItsRepeatCongestManager = NULL;
//---------------------------------------------------------------------------

/*
* RepeatCongest Manager
*/
TItsRepeatCongestManager::TItsRepeatCongestManager()
{
}
//---------------------------------------------------------------------------
TItsRepeatCongestManager::~TItsRepeatCongestManager()
{
}
//---------------------------------------------------------------------------
#include <time.h>
AnsiString GetWeekCode(AnsiString ANowTime)
{
    time_t      lCurTm;
    struct tm   tmNow, *psCurTm;

    sscanf(ANowTime.c_str(), "%04d%02d%02d%02d%02d%02d",
           &tmNow.tm_year, &tmNow.tm_mon, &tmNow.tm_mday,
           &tmNow.tm_hour, &tmNow.tm_min, &tmNow.tm_sec);

    tmNow.tm_year -= 1900; tmNow.tm_mon -= 1; tmNow.tm_isdst = -1;

    if ((lCurTm = mktime(&tmNow)) == -1)
    {
        return "-";
    }

    psCurTm = localtime(&lCurTm);

    // 0--6; Sunday = 0
    // 1--7; oracle, SELECt TO_CHAR(SYSDATE, 'D') FROM DUAL;, 주중의 일을 1~7로 표시(일요일이 1)

    switch(psCurTm->tm_wday)
    {
    case 1: return "DTW1"; break;   //	DTW	월요일	SUNDAY
    case 2: return "DTW2"; break;   //	DTW	화요일	MONDAY
    case 3: return "DTW3"; break;   //	DTW	수요일	WEDNESDAY
    case 4: return "DTW4"; break;   //	DTW	목요일	WEDNESDAY
    case 5: return "DTW5"; break;   //	DTW	금요일	WEDNESDAY
    case 6: return "DTW6"; break;   //	DTW	토요일	WEDNESDAY
    case 0: return "DTW7"; break;   //	DTW	일요일	SATURDAY
    }

    return "DTW0";  // 여기 들어올수 없음
}
//---------------------------------------------------------------------------

bool TItsRepeatCongestManager::LoadFromDb(TADOConnection *ADbConn/*=NULL*/)
{
    bool bResult = true;
    String sQry;
    TADOQuery *pADO = NULL;

#if 1
    String DAY_TYPE_CD = GetWeekCode(Now().FormatString("yyyymmddhhnnss"));
    sQry = "SELECT *                                            \r\n"
           "  FROM TB_REPT_CNGS_SECT                            \r\n"
           " WHERE STAT_YM = TO_CHAR(SYSDATE, 'YYYYMM')         \r\n"
           "   AND TO_CHAR(SYSDATE, 'HH24MI') >= CNFS_STRT_HM   \r\n"
           "   AND TO_CHAR(SYSDATE, 'HH24MI') <= CNFS_END_HM    \r\n"
           "   AND DAY_TYPE_CD = '" + DAY_TYPE_CD + "'";
#else
    sQry = "SELECT *                 \r\n"
           "  FROM TB_REPT_CNGS_SECT \r\n";
//           " ORDER BY IFSC_ID        \r\n";
#endif
    try
    {
        FDataSeq = 0;

        FLists.Lock();
        FListsCnfm.Lock();

        FLists.RemoveAll();
        FListsCnfm.RemoveAll();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = (NULL != ADbConn) ? ADbConn : ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            pADO->Prepared = true;
			pADO->Open();
            for( ; !pADO->Eof; pADO->Next())
            {
				TItsRepeatCongest *pRepeatCongest = new TItsRepeatCongest();

                pRepeatCongest->IFSC_ID		            = pADO->FieldByName("IFSC_ID")->AsString;                  // 정보제공구간 ID
                pRepeatCongest->STAT_YM		            = pADO->FieldByName("CRTN_YMD")->AsString;                  // 통계 년월
                pRepeatCongest->DAY_TYPE_CD	            = pADO->FieldByName("DAY_TYPE_CD")->AsString;              // 요일 유형 코드
                pRepeatCongest->CNFS_STRT_HM	        = pADO->FieldByName("CNFS_STRT_HM")->AsString;             // 혼잡 시작 시분
                pRepeatCongest->CNFS_END_HM	            = pADO->FieldByName("CNFS_END_HM")->AsString;              // 혼잡 종료 시분
                pRepeatCongest->AVRG_SPED		        = pADO->FieldByName("AVRG_SPED")->AsString;                // 평균 속도
                pRepeatCongest->AVRG_TRVL_HH	        = pADO->FieldByName("AVRG_TRVL_HH")->AsString;             // 평균 통행 시간
                pRepeatCongest->DCSN_YN		            = pADO->FieldByName("DCSN_YN")->AsString;                  // 확정 여부
                pRepeatCongest->CRTN_YMD		        = pADO->FieldByName("CRTN_YMD")->AsString;                 // 생성 일자
                pRepeatCongest->REPT_CNGS_SECT_ORGN_CD	= pADO->FieldByName("REPT_CNGS_SECT_ORGN_CD")->AsString;   // 반복 정체 구간 원본 코드

				if( pRepeatCongest->DCSN_YN != "Y" )
					FLists.Push(String(FDataSeq++), pRepeatCongest);
				else
					FListsCnfm.Push(String(FDataSeq++), pRepeatCongest);

                pRepeatCongest->Completed = true;
            }
        }
        catch(EDatabaseError &E)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDb", String(E.ClassName()), E.Message, sQry);
            return false;
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDb", String(exception.ClassName()), exception.Message, sQry);
            return false;
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        FLists.UnLock();
        FListsCnfm.UnLock();
    }

#if 1
    return bResult;
#else
    return LoadFromDbWthrCnfm(ADbConn);
#endif
}
//---------------------------------------------------------------------------

bool TItsRepeatCongestManager::LoadFromDbWthr(TADOConnection *ADbConn/*=NULL*/)
{
    bool bResult = true;
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT *                      \r\n"
           "  FROM TB_REPT_CNGS_SECT_WTHR \r\n";
//           " ORDER BY IFSC_ID             \r\n";
    try
    {
        FDataSeqWthr = 0;

        FListsWthr.Lock();
        FListsCnfmWthr.Lock();

        FListsWthr.RemoveAll();
        FListsCnfmWthr.RemoveAll();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = (NULL != ADbConn) ? ADbConn : ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            pADO->Prepared = true;
			pADO->Open();
            for( ; !pADO->Eof; pADO->Next())
            {
				TItsRepeatCongestWthr *pRepeatCongest = new TItsRepeatCongestWthr();

                pRepeatCongest->IFSC_ID		           = pADO->FieldByName("IFSC_ID")->AsString;                  // 정보제공구간 ID
                pRepeatCongest->CRTN_YMD		       = pADO->FieldByName("CRTN_YMD")->AsString;                 // 생성 일자
                pRepeatCongest->WTHR_TYPE_CD	       = pADO->FieldByName("WTHR_TYPE_CD")->AsString;             // 기상 코드
                pRepeatCongest->CNFS_STRT_HM	       = pADO->FieldByName("CNFS_STRT_HM")->AsString;             // 혼잡 시작 시분
                pRepeatCongest->CNFS_END_HM	           = pADO->FieldByName("CNFS_END_HM")->AsString;              // 혼잡 종료 시분
                pRepeatCongest->AVRG_SPED		       = pADO->FieldByName("AVRG_SPED")->AsString;                // 평균 속도
                pRepeatCongest->AVRG_TRVL_HH	       = pADO->FieldByName("AVRG_TRVL_HH")->AsString;             // 평균 통행 시간
                pRepeatCongest->DCSN_YN		           = pADO->FieldByName("DCSN_YN")->AsString;                  // 확정 여부
                pRepeatCongest->REPT_CNGS_SECT_ORGN_CD = pADO->FieldByName("REPT_CNGS_SECT_ORGN_CD")->AsString;   // 반복 정체 구간 원본 코드

				if( pRepeatCongest->DCSN_YN != "Y" )
					FListsWthr.Push(String(FDataSeqWthr++), pRepeatCongest);
				else
					FListsCnfmWthr.Push(String(FDataSeqWthr++), pRepeatCongest);

                pRepeatCongest->Completed = true;
            }
        }
        catch(EDatabaseError &E)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDbWthr", String(E.ClassName()), E.Message, sQry);
            return false;
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDbWthr", String(exception.ClassName()), exception.Message, sQry);
            return false;
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        FListsWthr.UnLock();
        FListsCnfmWthr.UnLock();
    }

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

bool TItsRepeatCongestManager::LoadFromDbWthrCnfm(TADOConnection *ADbConn/*=NULL*/)
{
    bool bResult = true;
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT *                      \r\n"
           "  FROM TB_REPT_CNGS_SECT_WTHR \r\n"
           " WHERE DCSN_YN = 'Y'          \r\n";
//           " ORDER BY IFSC_ID             \r\n";
    try
    {
        FDataSeqWthr = 0;

        FListsWthr.Lock();
        FListsCnfmWthr.Lock();

        FListsWthr.RemoveAll();
        FListsCnfmWthr.RemoveAll();
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = (NULL != ADbConn) ? ADbConn : ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            pADO->Prepared = true;
			pADO->Open();
            for( ; !pADO->Eof; pADO->Next())
            {
				TItsRepeatCongestWthr *pRepeatCongest = new TItsRepeatCongestWthr();

                pRepeatCongest->IFSC_ID		           = pADO->FieldByName("IFSC_ID")->AsString;                  // 정보제공구간 ID
                pRepeatCongest->CRTN_YMD		       = pADO->FieldByName("CRTN_YMD")->AsString;                 // 생성 일자
                pRepeatCongest->WTHR_TYPE_CD	       = pADO->FieldByName("WTHR_TYPE_CD")->AsString;             // 기상 코드
                pRepeatCongest->CNFS_STRT_HM	       = pADO->FieldByName("CNFS_STRT_HM")->AsString;             // 혼잡 시작 시분
                pRepeatCongest->CNFS_END_HM	           = pADO->FieldByName("CNFS_END_HM")->AsString;              // 혼잡 종료 시분
                pRepeatCongest->AVRG_SPED		       = pADO->FieldByName("AVRG_SPED")->AsString;                // 평균 속도
                pRepeatCongest->AVRG_TRVL_HH	       = pADO->FieldByName("AVRG_TRVL_HH")->AsString;             // 평균 통행 시간
                pRepeatCongest->DCSN_YN		           = pADO->FieldByName("DCSN_YN")->AsString;                  // 확정 여부
                pRepeatCongest->REPT_CNGS_SECT_ORGN_CD = pADO->FieldByName("REPT_CNGS_SECT_ORGN_CD")->AsString;   // 반복 정체 구간 원본 코드

				if( pRepeatCongest->DCSN_YN != "Y" )
					FListsWthr.Push(String(FDataSeqWthr++), pRepeatCongest);
				else
					FListsCnfmWthr.Push(String(FDataSeqWthr++), pRepeatCongest);

                pRepeatCongest->Completed = true;
            }
        }
        catch(EDatabaseError &E)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDbWthrCnfm", String(E.ClassName()), E.Message, sQry);
            return false;
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            ::PostMessage(Application->MainForm->Handle, (UINT)(WM_USER+0xF4), (WPARAM)0xB2, (LPARAM)0xB2);
            DBERRORLOG("TItsRepeatCongestManager::LoadFromDbWthrCnfm", String(exception.ClassName()), exception.Message, sQry);
            return false;
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        FListsWthr.UnLock();
        FListsCnfmWthr.UnLock();
    }

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

