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

#include <vcl.h>
#include <DateUtils.hpp>
#pragma hdrstop

#include "ITS_OPLibF.h"
#include "CDSCodeF.h"
#include "CDSVmsCtlrF.h"
#include "CDSVmsObjTypeF.h"

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

#pragma package(smart_init)

TITSLog            *ITSLog = NULL;
String              g_sMapDir = "";
int                 g_nMapSource = 1;
ST_GISINFO          g_GisInfo;
ST_SELLINK          g_SelLink;
APP_CONFIG          g_AppCfg;


TColor  g_DispColor[MAX_DISPCOLOR];
void APP_InitDisplayColor()
{
#if 0
    g_DispColor[ 0] = Graphics::clBlue;
    g_DispColor[ 1] = Graphics::clRed;
    g_DispColor[ 2] = Graphics::clLime;
    g_DispColor[ 3] = Graphics::clMaroon;
    g_DispColor[ 4] = Graphics::clGreen;
    g_DispColor[ 5] = Graphics::clMenuHighlight;
    g_DispColor[ 6] = Graphics::clBackground;
    g_DispColor[ 7] = Graphics::clPurple;
    g_DispColor[ 8] = Graphics::clTeal;
    g_DispColor[ 9] = Graphics::clYellow;
    g_DispColor[10] = Graphics::clFuchsia;
    g_DispColor[11] = Graphics::clAqua;
    g_DispColor[12] = Graphics::clMoneyGreen;
    g_DispColor[13] = Graphics::clSkyBlue;
    g_DispColor[14] = Graphics::clRed;
    g_DispColor[15] = Graphics::clLime;
    g_DispColor[16] = Graphics::clYellow;
    g_DispColor[17] = Graphics::clBlue;
    g_DispColor[18] = Graphics::clFuchsia;
    g_DispColor[19] = Graphics::clAqua;
    g_DispColor[20] = Graphics::clMoneyGreen;
    g_DispColor[21] = Graphics::clActiveCaption;
#else
    g_DispColor[ 0] = Graphics::clLime;
    g_DispColor[ 1] = (TColor)RGB(0xFF, 0x00, 0x00);
    g_DispColor[ 2] = (TColor)RGB(0x00, 0x00, 0xFF);
    g_DispColor[ 3] = (TColor)RGB(0xFF, 0x82, 0x00);
    g_DispColor[ 4] = (TColor)RGB(0x94, 0x00, 0xD3);
    g_DispColor[ 5] = (TColor)RGB(0x00, 0x00, 0x00);
    g_DispColor[ 6] = (TColor)RGB(0x82, 0x82, 0x82);
    g_DispColor[ 7] = (TColor)RGB(0x1E, 0x90, 0xFF);
    g_DispColor[ 8] = (TColor)RGB(0xB9, 0x06, 0x2F);
    g_DispColor[ 9] = (TColor)RGB(0x8c, 0x00, 0x8c);
    g_DispColor[10] = (TColor)RGB(0xFF, 0x82, 0x00);
    g_DispColor[11] = (TColor)RGB(0x94, 0x00, 0xD3);
    g_DispColor[12] = (TColor)RGB(0xB0, 0xC4, 0xDE);
    g_DispColor[13] = (TColor)RGB(0x00, 0xBF, 0xFF);
    g_DispColor[14] = (TColor)RGB(0x87, 0xCE, 0xEB);
    g_DispColor[15] = (TColor)RGB(0x87, 0xCE, 0xFA);
    g_DispColor[16] = (TColor)RGB(0xAD, 0xD8, 0xE6);
    g_DispColor[17] = (TColor)RGB(0xB0, 0xE0, 0xE6);
    g_DispColor[18] = (TColor)RGB(0xE6, 0xE6, 0xFA);
    g_DispColor[19] = (TColor)RGB(0xF0, 0xF8, 0xFF);
#endif
}
//---------------------------------------------------------------------------

TColor APP_GetDisplayColor(int ASeq)
{
    return g_DispColor[ASeq % MAX_DISPCOLOR];
}
//---------------------------------------------------------------------------

void APP_ImageClear(TCanvas *c, int offX, int offY, int w, int h, TColor color)
{
    try
    {
        c->Pen->Color = clWhite;
        c->Pen->Width = 0;
        c->Pen->Style = psClear;
        c->Brush->Style = bsSolid;
        c->Brush->Color = color;
        c->Rectangle(offX, offY, w+offX+2, h+offY+2);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

TDateTime APP_StrToDateTime(String AStrDateTime)
{
    TDateTime dtReturnValue = NULL;

    if (AStrDateTime.IsEmpty())      return dtReturnValue;
    if (AStrDateTime.Length() != 14) return dtReturnValue;

    AnsiString sDateTime = AnsiString(AStrDateTime);

    try
    {
#if 0
        sDateTime.printf(L"%s-%s-%s %s:%s:%s",
                           AStrDateTime.SubString( 1, 4).c_str(),
                           AStrDateTime.SubString( 5, 2).c_str(),
                           AStrDateTime.SubString( 7, 2).c_str(),
                           AStrDateTime.SubString( 9, 2).c_str(),
                           AStrDateTime.SubString(11, 2).c_str(),
                           AStrDateTime.SubString(13, 2).c_str());
        dtReturnValue = StrToDateTime(sDateTime);
#endif

// swscanf(sRgb.c_str(), L"%d,%d,%d", &r, &g, &b);

        int year, month, day, hour, minute, second;
        sscanf(sDateTime.c_str(), "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second);
        dtReturnValue = EncodeDateTime(year, month, day, hour, minute, second, 0);
    }
    catch(...)
    {
    }

    return dtReturnValue;
}
//---------------------------------------------------------------------------

void APP_ShowErrorMsg(String ATitle, String AErrMsg)
{
    Application->NormalizeTopMosts();
    Application->MessageBox(AErrMsg.c_str(), ATitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
    Application->RestoreTopMosts();
}
//----------------------------------------------------------------------------

String APP_FillCode(TcxComboBox *ACombo, String ACode)
{
    String sReturn = "";

    ACombo->Properties->Items->Clear();

    TItsCode *FCodeRMF  = ItsCodeManager->FLists.Find(ACode);
    if (FCodeRMF)
    {
		FOR_STL(TItsSubCode *, pSubCode, FCodeRMF->FSubLists)
		{
			if (pSubCode->USE_YN == "N") continue;
			ACombo->Properties->Items->Add(" [" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM);
            if (sReturn == "")
            {
                sReturn = " [" + pSubCode->CMMN_CD + "] " + pSubCode->CMMN_CD_KOR_NM;
            }
		}
    }
	ACombo->ItemIndex = 0;
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCode(TcxComboBox *ACombo)
{
    String sReturn = "";

    if (ACombo->ItemIndex >= 0)
    {
        String sDesc = ACombo->Properties->Items->Strings[ACombo->ItemIndex];
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        sReturn = sCode;
    }
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCodeName(TcxComboBox *ACombo, String ACode)
{
    String sReturn = "";
    for (int ii = 0; ii < ACombo->Properties->Items->Count; ii++)
    {
        String sDesc = ACombo->Properties->Items->Strings[ii];
        String sName = sDesc.SubString(sDesc.Pos("]") + 1, sDesc.Length());
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        if (ACode == sCode)
        {
            sReturn = sName.Trim();
            break;
        }
    }
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCodeIdByName(TcxComboBox *ACombo, String AName)
{
    String sReturn = "3";
    for (int ii = 0; ii < ACombo->Properties->Items->Count; ii++)
    {
        String sDesc = ACombo->Properties->Items->Strings[ii];
        String sName = sDesc.SubString(sDesc.Pos("]") + 1, sDesc.Length());
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        if (sName.Trim() == AName.Trim())
        {
            sReturn = sCode;
            break;
        }
    }
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCodeDesc(TcxComboBox *ACombo, String ACode)
{
    String sReturn = "";

    for (int ii = 0; ii < ACombo->Properties->Items->Count; ii++)
    {
        String sDesc = ACombo->Properties->Items->Strings[ii];
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        if (ACode == sCode)
        {
            sReturn = sDesc;
            break;
        }
    }
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCodeDefCode(TcxComboBox *ACombo)
{
    String sReturn = "";

    if (ACombo->Properties->Items->Count > 0)
    {
        String sDesc = ACombo->Properties->Items->Strings[0];
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        sReturn = sCode;
    }
    return sReturn;
}
//----------------------------------------------------------------------------

String APP_GetCodeDefDesc(TcxComboBox *ACombo)
{
    String sReturn = "";

    if (ACombo->Properties->Items->Count > 0)
    {
        String sDesc = ACombo->Properties->Items->Strings[0];
        sReturn = sDesc;
    }
    return sReturn;
}
//----------------------------------------------------------------------------

int APP_SetCode(TcxComboBox *ACombo, String ACode)
{
    int nItemIndex = -1;

    for (int ii = 0; ii < ACombo->Properties->Items->Count; ii++)
    {
        String sDesc = ACombo->Properties->Items->Strings[ii];
        String sCode = sDesc.SubString(sDesc.Pos("[") + 1,
                                       sDesc.Pos("]") - (sDesc.Pos("[") + 1));
        if (ACode == sCode)
        {
            nItemIndex = ii;
            break;
        }
    }
    ACombo->ItemIndex = nItemIndex;
    return nItemIndex;
}
//----------------------------------------------------------------------------

void APP_DelVmsSizeCombo(TcxComboBox *cboBox)
{
    TStrings     *pStrItems;
    TVmsSizeType *Ov;

    pStrItems = ((TcxComboBox *)cboBox)->Properties->Items;

    for (int ii = pStrItems->Count-1; ii >= 0; ii--)
    {
        Ov = (TVmsSizeType *)pStrItems->Objects[ii];

        if (Ov != NULL)
        {
            delete Ov;
            Ov = NULL;
        }
    }
}
//---------------------------------------------------------------------------

void APP_FillVmsSizeType(TcxComboBox *cboBox, bool bAddAll/*=false*/)
{
    String     sQry;
    TStrings  *pStrItems;
    TADOQuery *pADO = NULL;

    APP_DelVmsSizeCombo(cboBox);

    pStrItems = ((TcxComboBox *)cboBox)->Properties->Items;
    ((TcxComboBox *)cboBox)->Properties->Items->Clear();

    FOR_STL(TVmsType*, pObj, VmsTypeManager->FLists)
    {
        String sTypeCd = pObj->VMS_TYPE_CD;
        String sTypeNm = pObj->VMS_TYPE_NM;
        int nW = pObj->VMS_WDTH;
        int nH = pObj->VMS_HGHT;
        pStrItems->AddObject(" [" + sTypeCd + "] " + sTypeNm + " (" + String(nW) + "x" + String(nH) + ")", new TVmsSizeType(sTypeCd, sTypeNm, nW, nH) );
    }
    if (bAddAll)
    {
        String sAllName = "전체";
        pStrItems->AddObject(" [ALL] 전체" , new TVmsSizeType("ALL", sAllName, 384, 64));
    }
    cboBox->ItemIndex = 0;
}
//---------------------------------------------------------------------------

TVmsSizeType* APP_GetVmsSizeTypeObject(TcxComboBox *cboBox)
{
    TStrings     *pStrItems;
    TVmsSizeType *Ov = NULL;
    int           nItemIndex;

    pStrItems = ((TcxComboBox *)cboBox)->Properties->Items;
    nItemIndex= ((TcxComboBox *)cboBox)->ItemIndex;

    if (nItemIndex < 0)
    {
        return Ov;
    }

    Ov = (TVmsSizeType *)pStrItems->Objects[nItemIndex];

    if (Ov == NULL)
    {
        Ov = NULL;
    }

    return Ov;
}
//---------------------------------------------------------------------------

bool APP_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;
}
//---------------------------------------------------------------------------

String APP_FormatStr(String AStrDateTime, String AFormat)
{
#define SYEAR "-"
#define STIME ":"
#define SPACE " "

    String sDateTime = "";
    String sInData   = AStrDateTime;//AnsiString(AStrDateTime);
    String sFormat   = AFormat;

    if (sInData.IsEmpty())
        return sInData;

    try
    {
        if (sFormat == STR_DATETIME)
        {
            if (sInData.Length() < 14) return sInData;
            sDateTime = sInData.SubString( 1, 4) + SYEAR +
                        sInData.SubString( 5, 2) + SYEAR +
                        sInData.SubString( 7, 2) + SPACE +
                        sInData.SubString( 9, 2) + STIME +
                        sInData.SubString(11, 2) + STIME +
                        sInData.SubString(13, 2);
        }
        else
        if (sFormat == STR_HHNN)
        {
            if (sInData.Length() < 12) return sInData;
            sDateTime = sInData.SubString( 1, 4) + SYEAR +
                        sInData.SubString( 5, 2) + SYEAR +
                        sInData.SubString( 7, 2) + SPACE +
                        sInData.SubString( 9, 2) + STIME +
                        sInData.SubString(11, 2);
        }
        else
        if (sFormat == STR_DATEHOUR)
        {
            if (sInData.Length() < 10) return sInData;
            sDateTime = sInData.SubString( 1, 4) + SYEAR +
                        sInData.SubString( 5, 2) + SYEAR +
                        sInData.SubString( 7, 2) + SPACE +
                        sInData.SubString( 9, 2);
        }
        else
        if (sFormat == STR_DATE)
        {
            if (sInData.Length() < 8) return sInData;
            sDateTime = sInData.SubString( 1, 4) + SYEAR +
                        sInData.SubString( 5, 2) + SYEAR +
                        sInData.SubString( 7, 2);
        }
        else
        if (sFormat == STR_MM)
        {
            if (sInData.Length() < 6) return sInData;
            sDateTime = sInData.SubString( 1, 4) + SYEAR +
                        sInData.SubString( 5, 2);
        }
        else
        {
            sDateTime = sInData;
        }

    }
    catch(Exception &E)
    {
        throw Exception(String(E.ClassName()) + E.Message);
    }

    return sDateTime;
}
//---------------------------------------------------------------------------

void APP_SetSummaryItemKind(TcxSummaryEventArguments    &Arguments,
                            TcxSummaryEventOutArguments &OutArguments,
                            int                         pKind,
                            bool                        pCaptionDisplay,
                            bool                        pPointDisplay)
{
#if 0
    String    sAvgCaption, sSumCaption, sMinCaption, sMaxCaption, sCntCaption;

    sAvgCaption = "";
    sMinCaption = "";
    sMaxCaption = "";
    //sCntCaption = "";
    sSumCaption = "";

    if (pCaptionDisplay)
    {
        sAvgCaption = "";//"평균: ";
        sMinCaption = "최소: ";
        sMaxCaption = "최대: ";
        if (pKind == 1)
        {
            sSumCaption = "소계: ";
        }
        else
        {
            sSumCaption = "합계: ";
        }
    }

    //sCntCaption = " 건";
#endif
#if 0
    if (VarIsNull(OutArguments.Value))
    {
        OutArguments.Done = true;
        return;
    }
#endif
#if 0
    if (Arguments.SummaryItem->Kind == skSum)
    {
        if (!VarIsNull(OutArguments.Value))
        {
            if (!VarSameValue(OutArguments.Value, Variant(0)))
            {
                OutArguments.CountValue++;
                OutArguments.SummaryValue += OutArguments.Value;
                OutArguments.Done = true;
            }
            else
            {
                //OutArguments.CountValue--;
                OutArguments.Done = true;
            }
        }
        else
        {
            //OutArguments.CountValue--;
            OutArguments.Done = true;
        }
    }
    else
#endif
    if (Arguments.SummaryItem->Kind == skAverage)
    {
        if (!VarIsNull(OutArguments.Value))
        {
            if (!VarSameValue(OutArguments.Value, Variant(0)))
            {
                OutArguments.CountValue++;
                //OutArguments.Value = Variant(0);
                OutArguments.SummaryValue += OutArguments.Value;
                OutArguments.Done = true;
            }
            else
            {
                //OutArguments.CountValue--;
                OutArguments.Done = true;
            }
        }
        else
        {
            //OutArguments.CountValue--;
            OutArguments.Done = true;
        }
#if 0
        if (pPointDisplay)
            Arguments.SummaryItem->Format = sAvgCaption + "#,##0.0";
        else
            Arguments.SummaryItem->Format = sAvgCaption + "#,##0";
#endif
    }
#if 0
    else if (Arguments.SummaryItem->Kind == skSum)
        Arguments.SummaryItem->Format = sSumCaption + "#,##0.##";
    else if (Arguments.SummaryItem->Kind == skMin)
        Arguments.SummaryItem->Format = sMinCaption + "#,##0.##";
    else if (Arguments.SummaryItem->Kind == skMax)
        Arguments.SummaryItem->Format = sMaxCaption + "#,##0.##";
    else if (Arguments.SummaryItem->Kind == skCount)
        Arguments.SummaryItem->Format = "#,##0"     + sCntCaption;
#endif
}
//---------------------------------------------------------------------------

ULONG ProcIDFromWnd(HWND hwnd) // 윈도우 핸들로 프로세스 아이디 얻기
{
  ULONG idProc;
  GetWindowThreadProcessId( hwnd, &idProc );
  return idProc;
}
//----------------------------------------------------------------------------

HWND GetWinHandle(ULONG pid) // 프로세스 아이디로 윈도우 핸들 얻기
{
  HWND tempHwnd = FindWindow(NULL,NULL); // 최상위 윈도우 핸들 찾기

  while( tempHwnd != NULL )
  {
    if( GetParent(tempHwnd) == NULL ) // 최상위 핸들인지 체크, 버튼 등도 핸들을 가질 수 있으므로 무시하기 위해
      if( pid == ProcIDFromWnd(tempHwnd) )
        return tempHwnd;
    tempHwnd = GetWindow(tempHwnd, GW_HWNDNEXT); // 다음 윈도우 핸들 찾기
  }
  return NULL;
}
//----------------------------------------------------------------------------

//DeleteLogFiles((PTCHAR)g_sLogDir.c_str(), 30, (PTCHAR)"*.*");
//bool DeleteLogFiles(PTCHAR pszPath, int nDays, PTCHAR pszFile);

#include <windows.h>
#include <shlwapi.h>
#pragma comment (lib, "shlwapi.lib")
bool APP_IsDirectoryExists(LPCTSTR path)
{
    return PathFileExists(path);
#if 0
    struct _stat buffer;
    int          iRetTemp = 0;

    memset((void*)&buffer, 0, sizeof(buffer));
    iRetTemp = _stat(path, &buffer);
    if (iRetTemp == 0)
    {
        if (buffer.st_mode & _S_IFDIR)
        {
            return true;
        }
    }
    return false;
#endif
}
//---------------------------------------------------------------------------


