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

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "AppGlobalF.h"
#include "ITSLangTransF.h"
#pragma hdrstop

#include "VMSM900MF.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxButtons"
#pragma link "cxCalendar"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxDropDownEdit"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxGroupBox"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxMaskEdit"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "cxSpinEdit"
#pragma link "cxSplitter"
#pragma link "cxTextEdit"
#pragma link "cxTimeEdit"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinCaramel"
#pragma link "dxSkinCoffee"
#pragma link "dxSkinDarkRoom"
#pragma link "dxSkinDarkSide"
#pragma link "dxSkinFoggy"
#pragma link "dxSkinGlassOceans"
#pragma link "dxSkiniMaginary"
#pragma link "dxSkinLilian"
#pragma link "dxSkinLiquidSky"
#pragma link "dxSkinLondonLiquidSky"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinMoneyTwins"
#pragma link "dxSkinOffice2007Black"
#pragma link "dxSkinOffice2007Blue"
#pragma link "dxSkinOffice2007Green"
#pragma link "dxSkinOffice2007Pink"
#pragma link "dxSkinOffice2007Silver"
#pragma link "dxSkinOffice2010Black"
#pragma link "dxSkinOffice2010Blue"
#pragma link "dxSkinOffice2010Silver"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinSeven"
#pragma link "dxSkinSharp"
#pragma link "dxSkinSilver"
#pragma link "dxSkinStardust"
#pragma link "cxRadioGroup"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDBData"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridDBTableView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxStyles"
#pragma link "cxCheckBox"
#pragma link "cxCalc"
#pragma resource "*.dfm"

TVMSM900M *VMSM900M = NULL;
//---------------------------------------------------------------------------

__fastcall TVMSM900M::TVMSM900M(TComponent* Owner)
    : TForm(Owner)
{
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Load(this);
    CMM_LoadForm(g_sFormsDir, this);

    FUpdate= false;
    FTitle = Caption;//"VMS 휘도설정 스케줄 관리";

    EditMode = false;

    FillVmsList();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::CommClose()
{
    try
    {
        CMM_SaveForm(g_sFormsDir, this);
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::FormShow(TObject *Sender)
{
    Refresh();

    FormInit();
    ChangeEditMode(1);
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::FormInit()
{
    EdNmbr->Text = "";
    EdTime->Text = "";

	CbVms->ItemIndex = 0;
    SeLuminance->Value = 0;
	CbUseYn->ItemIndex = 0;

	CxSchTime->Clear();
    CxSchTime->EditValue = Now().FormatString("hh:nn");
    CxSchTime->EditValue = "00:00";

    FNewDb = false;
}
//---------------------------------------------------------------------------

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

    UpdateList();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::BtnCloseClick(TObject *Sender)
{
    Close();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    VMSM900M = NULL;
    Action = caFree;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    if (FUpdate)
    {
        POST_MSG(Application->MainForm->Handle, WM_DATABASE_REFRESH, WP_MSG_14, 0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::DisplayInfo()
{
    FormInit();

	int nRow = TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    String VmsNo = TvList->DataController->Values[nRow][Column01->Index];

    String SchTm = TvList->DataController->Values[nRow][Column07->Index];
    int    Lumin = TvList->DataController->Values[nRow][Column08->Index];
    String UseYn = TvList->DataController->Values[nRow][Column09->Index];

    APP_SetCode(CbVms, VmsNo);
    APP_SetCode(CbUseYn, UseYn);
    SeLuminance->Value = Lumin;

    EdNmbr->Text = VmsNo;
    EdTime->Text = SchTm;

    try
    {
        if (SchTm.Length() == 4)                        // 전팡관ON시각
        {
            SchTm.Insert(":", 3);
            CxSchTime->EditValue = SchTm;
        }
    }
    catch(Exception &e)
    {
    }

    ChangeEditMode(3);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::BtnEditClick(TObject *Sender)
{
    if (BtnEdit->Caption == FrmLang->lblEdit->Caption)//"편집")
    {
        ChangeEditMode(0);
        FNewDb = false;
    }
    else
    {
        String VmsNo = EdNmbr->Text;
        String SchTm = EdTime->Text;
        ChangeEditMode(1);

        CMM_SetGridDataFocus2(TvList->DataController, VmsNo, Column01->Index, SchTm, Column07->Index);
        DisplayInfo();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::ChangeEditMode(int AEdit)
{
    bool bEnabled = false;
    switch(AEdit)
    {
    case 0: //편집버튼클릭
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = FrmLang->lblCancel->Caption;//"취소";
            BtnEdit->Hint    = FrmLang->lblCancel->Hint;//데이터 편집 취소";
            EditMode = true;
        }
        break;
    case 1: //편집[취소]버튼클릭
        {
            FormInit(); //화면을 모두 지운다.
            BtnEdit->Enabled = false;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = false;

            BtnEdit->Caption = FrmLang->lblEdit->Caption;//"편집";
            BtnEdit->Hint    = FrmLang->lblEdit->Hint;//데이터 편집";
            //bEnabled = true;
            EditMode = false;
        }
        break;
    case 2: //추가
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = false;
            BtnDelete->Enabled = false;
            BtnSave->Enabled = true;

            BtnEdit->Caption = FrmLang->lblCancel->Caption;//"취소";
            BtnEdit->Hint    = FrmLang->lblCancel->Hint;//데이터 편집 취소";
            EditMode = true;
        }
        break;
    case 3: //수정모드
        {
            BtnEdit->Enabled = true;
            BtnInsert->Enabled = true;
            BtnDelete->Enabled = true;
            BtnSave->Enabled = false;

            BtnEdit->Caption = FrmLang->lblEdit->Caption;//"편집";
            BtnEdit->Hint    = FrmLang->lblEdit->Hint;//데이터 편집";
            bEnabled = true;
            EditMode = false;
        }
        break;
    }

    if (AEdit == 2)
    {
        CbVms->Enabled = true;
        CxSchTime->Enabled = true;
    }
    else
    {
        CbVms->Enabled = false;
        CxSchTime->Enabled = false;
    }

    if (AEdit == 0 || AEdit == 2)
    {
        CxList->Enabled = false;
    }
    else
    {
        CxList->Enabled = true;
    }

    PnlEdit->Enabled = EditMode;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::BtnInsertClick(TObject *Sender)
{
    FormInit();
    //신규아이디를 얻어와서 화면을 초기화한다.

    ChangeEditMode(2);
    FNewDb = true;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::BtnDeleteClick(TObject *Sender)
{
    int nRow = TvList->DataController->FocusedRecordIndex;
    if (nRow < 0) return;

    String VmsNo = TvList->DataController->Values[nRow][Column01->Index];
    String SchTm = TvList->DataController->Values[nRow][Column07->Index];

    String sMsg;
    sMsg = lblText1->Caption + ": " + VmsNo;//"VMS번호: " + VmsNo;
    sMsg+= "\r\n" +lblText2->Caption + ": " + SchTm;
    sMsg+= "\r\n" + lblText3->Caption;//"선택하신 휘도제어 스케줄 정보를 삭제하시겠습니까?";

    if (Application->MessageBox(sMsg.c_str(), FTitle.c_str(), MB_YESNO|MB_ICONQUESTION|MB_APPLMODAL) != IDYES) return;

    if (DeleteInfo(VmsNo, SchTm))
    {
        UpdateList();
    }

    FUpdate = true;

    Application->MessageBox(lblText4->Caption.c_str(),//L"휘도제어 스케줄 정보삭제\r\휘도제어 스케줄 정보를 삭제 하였습니다.",
                            FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

    FormInit();
    ChangeEditMode(1);

}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::BtnSaveClick(TObject *Sender)
{
    String VmsNo = APP_GetCode(CbVms);
    String SchTm = CxSchTime->Time.FormatString("HHNN");

	if (VmsNo.IsEmpty() || SchTm.IsEmpty())
	{
        Application->MessageBox(FrmLang->lblNecessary->Caption.c_str(),//L"★항목은 필수 입력 항목입니다.\r\n모두 입력후 진행해 주세요.",
                                FTitle.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
		return;
	}

    String Lumin = SeLuminance->Value;
    String UseYn = APP_GetCode(CbUseYn);

    if (MergeInfo(VmsNo, SchTm, Lumin, UseYn))
    {
        Application->MessageBox(lblText4->Caption.c_str(),//L"휘도제어 스케줄 정보저장\r\n휘도제어 스케줄 정보를 저장 하였습니다.",
                                FTitle.c_str(), MB_OK|MB_ICONINFORMATION|MB_APPLMODAL);

        FUpdate = true;

        UpdateList();
        CMM_SetGridDataFocus2(TvList->DataController, VmsNo, Column01->Index, SchTm, Column07->Index);
        DisplayInfo();
    }
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::SeLuminancePropertiesChange(TObject *Sender)
{
    if (((TcxSpinEdit*)Sender)->Value < ((TcxSpinEdit*)Sender)->Properties->MinValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MinValue;
    else if(((TcxSpinEdit*)Sender)->Value > ((TcxSpinEdit*)Sender)->Properties->MaxValue &&
        ((TcxSpinEdit*)Sender)->Properties->MaxValue)
        ((TcxSpinEdit*)Sender)->Value = ((TcxSpinEdit*)Sender)->Properties->MaxValue;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::FillVmsList()
{
    CbVms->Properties->Items->Clear();

    VmsCtlrManager->FLists.Lock();
    try
    {
        FOR_STL(TVmsCtlr*, pObj, VmsCtlrManager->FLists)
        {
            if (pObj->DEL_YN == "Y") continue;

            String NO = String(pObj->VMS_CTLR_NMBR);
            String ID = pObj->VMS_CTLR_ID;
            String NM = pObj->VMS_NM;

			CbVms->Properties->Items->Add(" [" + NO + "] (" + ID + ") " + NM);
        }
    }
    __finally
    {
        VmsCtlrManager->FLists.UnLock();
    }
}
//---------------------------------------------------------------------------

bool __fastcall TVMSM900M::MergeInfo(String AVmsNo, String ASchTm, String ALuminance, String AUseYn)
{
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "MERGE INTO TB_VMS_LUM_SET_SCH L                \r\n"
           "USING (SELECT :p01 AS VMS_CTLR_NMBR,           \r\n"
           "              :p02 AS SCH_TIME,                \r\n"
           "              :p03 AS LUMINANCE,               \r\n"
           "              :p04 AS USE_YN                   \r\n"
           "         FROM DUAL) M                          \r\n"
           "        ON (L.VMS_CTLR_NMBR = M.VMS_CTLR_NMBR  \r\n"
           "        AND L.SCH_TIME      = M.SCH_TIME)      \r\n"
           "WHEN MATCHED                                   \r\n"
           "THEN                                           \r\n"
           "   UPDATE SET L.LUMINANCE = M.LUMINANCE,       \r\n"
           "              L.USE_YN    = M.USE_YN           \r\n"
           "WHEN NOT MATCHED                               \r\n"
           "THEN                                           \r\n"
           "   INSERT (VMS_CTLR_NMBR,                      \r\n"
           "           SCH_TIME,                           \r\n"
           "           LUMINANCE,                          \r\n"
           "           USE_YN )                            \r\n"
           "   VALUES (M.VMS_CTLR_NMBR,                    \r\n"
           "           M.SCH_TIME,                         \r\n"
           "           M.LUMINANCE,                        \r\n"
           "           M.USE_YN )                          \r\n";

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            pADO->Parameters->ParamByName("p01")->Value = AVmsNo;
            pADO->Parameters->ParamByName("p02")->Value = ASchTm;
            pADO->Parameters->ParamByName("p03")->Value = ALuminance;
            pADO->Parameters->ParamByName("p04")->Value = AUseYn;
			pADO->ExecSQL();

            return true;
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
    return false;
}
//---------------------------------------------------------------------------

bool __fastcall TVMSM900M::DeleteInfo(String AVmsNo, String ASchTm)
{
    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "DELETE TB_VMS_LUM_SET_SCH    \r\n"
           " WHERE VMS_CTLR_NMBR = :p01  \r\n"
           "   AND SCH_TIME      = :p02  \r\n";

    try
    {
        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();
			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;

            pADO->Parameters->ParamByName("p01")->Value = AVmsNo;
            pADO->Parameters->ParamByName("p02")->Value = ASchTm;
			pADO->ExecSQL();

            return true;
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &exception)
        {
            throw Exception(String(exception.ClassName()) + exception.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::UpdateList()
{
    CMM_ClearGridTableView(TvList);
    TcxDataController *pGDC = TvList->DataController;

    String sQry;
    TADOQuery *pADO = NULL;

    sQry = "SELECT A.VMS_CTLR_NMBR, A.SCH_TIME, A.LUMINANCE, A.USE_YN, \r\n"
           "       B.VMS_CTLR_ID, B.VMS_NM                             \r\n"
           "  FROM TB_VMS_LUM_SET_SCH A,                               \r\n"
           "       TB_VMS_CTLR        B                                \r\n"
           " WHERE A.VMS_CTLR_NMBR = B.VMS_CTLR_NMBR                   \r\n"
           "   AND B.DEL_YN        = 'N'                               \r\n";

    int nRowHeight = 0;
    try
    {
        int nRow;
        TvList->BeginUpdate();
        pGDC->BeginUpdate();

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

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

            for( ; !pADO->Eof; pADO->Next())
            {
                nRow = pGDC->AppendRecord();

                String VmsNo = pADO->FieldByName("VMS_CTLR_NMBR")->AsString;
                String VmsId = pADO->FieldByName("VMS_CTLR_ID")->AsString;
                String VmsNm = pADO->FieldByName("VMS_NM")->AsString;
                String SchTm = pADO->FieldByName("SCH_TIME")->AsString;
                String Lumin = pADO->FieldByName("LUMINANCE")->AsString;
                String UseYn = pADO->FieldByName("USE_YN")->AsString;

                pGDC->Values[nRow][Column01->Index] = VmsNo;
                pGDC->Values[nRow][Column02->Index] = VmsId;
                pGDC->Values[nRow][Column03->Index] = VmsNm;
                pGDC->Values[nRow][Column04->Index] = SchTm;
                pGDC->Values[nRow][Column05->Index] = Lumin;
                if (UseYn == "Y")
                    pGDC->Values[nRow][Column06->Index] = "사용";
                else
                    pGDC->Values[nRow][Column06->Index] = "사용안함";

                pGDC->Values[nRow][Column07->Index] = SchTm;
                pGDC->Values[nRow][Column08->Index] = Lumin.ToIntDef(0);
                pGDC->Values[nRow][Column09->Index] = UseYn;
            }
        }
        catch(EDatabaseError &E)
        {
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            throw Exception(String(e.ClassName()) + e.Message);
        }
    }
    __finally
    {
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
        pGDC->EndUpdate();
        TvList->EndUpdate();
    }
    CMM_ExpandCollapseChk(TvList, ChkExpand->Checked);
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::TvListCellDblClick(TcxCustomGridTableView *Sender, TcxGridTableDataCellViewInfo *ACellViewInfo,
          TMouseButton AButton, TShiftState AShift,
          bool &AHandled)
{
	if (!ACellViewInfo) return;
	int nRow = TvList->DataController->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    //DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::TvListFocusedRecordChanged(TcxCustomGridTableView *Sender,
          TcxCustomGridRecord *APrevFocusedRecord, TcxCustomGridRecord *AFocusedRecord,
          bool ANewItemRecordFocusingChanged)
{
    if (TvList->ViewData->RecordCount <= 0) return;
    if (TvList->DataController->FocusedRowIndex < 0) return;

    TcxDataController *pGDC = TvList->DataController;
    int nRow = pGDC->FocusedRecordIndex;
	if( nRow <= -1 )
		return;

    DisplayInfo();
}
//---------------------------------------------------------------------------

void __fastcall TVMSM900M::ChkExpandClick(TObject *Sender)
{
    CMM_ExpandCollapseChk(TvList, ChkExpand->Checked);
}
//---------------------------------------------------------------------------

