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

#include <vcl.h>
//#include "ITSDbF.h"
//#include "ITSUtilF.h"
//#include "AppGlobalF.h"
#pragma hdrstop

#include "XnsCommon.h"
#include "XnsDeviceInterface.h"
#include "FrmVmsCamOldF.h"
#include "AppGlobalF.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "XNSSDKWINDOWLib_OCX"
#pragma link "XNSSDKDEVICELib_OCX"
#pragma link "XNSSDKDEVICELib_OCX"
#pragma resource "*.dfm"

//TFrmVmsCam *FrmVmsCam = NULL;

//---------------------------------------------------------------------------
__fastcall TFrmVmsCamOld::TFrmVmsCamOld(TComponent* Owner)
    : TForm(Owner)
{
    //::CoInitialize(NULL);

    FDispBlob = false;

    XnsSdkDevice1->Left = -500;
    XnsSdkWindow1->Parent = PnlClient;
    XnsSdkWindow1->Align  = alClient;

	m_hDevice      = 0;     // Device handle
	m_hMediaSource = 0;		// Media stream ID
	m_nControlId   = 0;		// Control ID
	m_bIsMediaPlay = false;
}
//---------------------------------------------------------------------------

/*
 * form을 보여줄때 호출되는 event 메서드이다.
 *  arguments
 *      Sender : event handler 객체
 *  return
 *      void
 */
void __fastcall TFrmVmsCamOld::FormShow(TObject *Sender)
{
    RefreshVms();
    TmrShow->Enabled = true;
}
//---------------------------------------------------------------------------

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

    try
    {
        if (FObj)
        {
            Caption = FObj->VMS_CTLR_ID;// + ": " + FObj->VMS_NM;
            WebCamPlay();
        }
    }
    catch(...){}
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmVmsCamOld::FormDestroy(TObject *Sender)
{
    try {
        if (FObj)
        {
            FObj->FData2 = NULL;
        }
        WebCamStop();
        //ReleaseWebCamera();
    } catch(...) {}
}
//---------------------------------------------------------------------------

/*
 * 닫기버튼 이나 x버튼 클릭시 공통으로 처리하는 로직이들어간다..
 * Form과 DataModule class를 delete시킨다.
 *  arguments
 *
 *  return
 *      void
 */
void __fastcall TFrmVmsCamOld::CommClose()
{
    //FrmVmsCam = NULL;
    //::CoUninitialize();
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::WebCamPlay()
{
    TItsVms *pVmsObj = FObj;
    if (!pVmsObj) return;
    
    if (!SetupWebCamera()) return;
    
    try
    {
        // 신규 영상 연결
        ConnectWebCamera();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::WebCamStop()
{
    try {
        DisconnectWebCamera();
    } catch(...) {}
}
//---------------------------------------------------------------------------

bool __fastcall TFrmVmsCamOld::SetupWebCamera()
{
    String sErrMsg;

	long nRet = XnsSdkDevice1->Initialize();
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sErrMsg.printf(L"Samsung XnsSdkDevice Initialize() fail: return=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
	}

	//nRet = XnsSdkWindow1->Initialize((long)PnlClient->Handle, NULL);
	nRet = XnsSdkWindow1->Initialize(NULL, NULL);
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sErrMsg.printf(L"Samsung XnsSdkWindow Initialize() fail: return=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
	}

	m_lDeviceId = XnsSdkDevice1->CreateDeviceEx();
	m_hDevice = XnsSdkDevice1->GetDeviceHandle(m_lDeviceId);
	if (m_hDevice == 0)
	{
		sErrMsg = "CreateDevice() fail";
        Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        return false;
	}

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

void __fastcall TFrmVmsCamOld::ReleaseWebCamera()
{
	if (m_hDevice != 0)
    {
		if (m_hMediaSource)
		{
			XnsSdkWindow1->Stop();
			XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);
		}
		if (XnsSdkDevice1->GetDeviceStatus(m_hDevice) == XDEVICE_STATUS_CONNECTED)
		{
			XnsSdkDevice1->Disconnect(m_hDevice);
		}
    	//XnsSdkDevice1->ReleaseDevice(m_hDevice);
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFrmVmsCamOld::ConnectWebCamera()
{
    bool       bConnect   = true;

    if (!FObj) return false;

    WideString sDefModel  = "Samsung";
    WideString sModelName = "SNP-3371TH";
    WideString sIpAddress = FObj->WEB_CMRA_IP;

    int        nPort      = FObj->WEB_CMRA_PORT.ToIntDef(4520);
    WideString sID        = FObj->WEB_CMRA_ID;
    WideString sPass      = FObj->WEB_CMRA_PSWD;


    sDefModel  = WideString(g_AppCfg.vmscam.sComModel);
    sModelName = WideString(g_AppCfg.vmscam.sDevModel);

	XnsSdkDevice1->SetConnectionInfo(
		m_hDevice,					            // [in] Device handle
		sDefModel.Detach(),				        // [in] Fixed as 'Samsung'
		sModelName.Detach(),				    // [in] Name of model to connect to. The maximum length allowed is 126-byte.
		XADDRESS_IP, sIpAddress.Detach(),	    // [in] Address type, actual address according to addresstype.
		nPort, 0,					            // [in] Port number, port number for web access
		sID.Detach(), sPass.Detach()		    // [in] Login ID, password
		);

	long nRet = XnsSdkDevice1->ConnectNonBlock(
		m_hDevice,		// [in] Device handle
		false,			// [in] Flag to decide where to forcibly log in or not.
		false			// [in] If this value is 1, try to connect again.
		);
	if (nRet != ERR_SUCCESS)
	{
        String sErrMsg;
    	sErrMsg.printf(L"ConnectNonBlock() fail: errno=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        bConnect = false;
	}

    return bConnect;
}
//---------------------------------------------------------------------------

bool __fastcall TFrmVmsCamOld::OpenWebCamera()
{
    XnsSdkDevice1->OpenMedia(m_hDevice, 3, MEDIA_TYPE_LIVE, 0, 0, &m_hMediaSource);
    XnsSdkWindow1->Start(m_hMediaSource);

    m_nControlId = 3;
    m_bIsMediaPlay = true;

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

void __fastcall TFrmVmsCamOld::DisconnectWebCamera()
{
    if (m_hDevice == 0) return;
    
	CloseWebCamera();

	// Disconnects from the device.
    if (XnsSdkDevice1->GetDeviceStatus(m_hDevice) == XDEVICE_STATUS_CONNECTED)
    {
        XnsSdkDevice1->Disconnect(m_hDevice);
    }

    XnsSdkDevice1->ReleaseDevice(m_hDevice);

	m_bIsMediaPlay = false;
	m_hMediaSource = 0;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::CloseWebCamera()
{
	if (!m_hMediaSource) 
	{
		return;
	}

	if (m_bIsMediaPlay)
	{
        XnsSdkWindow1->Stop();
        m_bIsMediaPlay = false;
	}

	XnsSdkDevice1->CloseMedia(m_hDevice, m_hMediaSource);

	m_hMediaSource = 0;
	m_nControlId   = 0;                                       
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::XnsSdkDevice1ConnectFailed(TObject *Sender, long nDeviceID, long nControlID)
{
    //Caption = Caption + " - Connect Failed.";
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::XnsSdkDevice1DeviceStatusChanged(TObject *Sender, long nDeviceID, long nErrorCode, long nDeviceStatus,
          long nHddCondition)
{
    if (nErrorCode == ERR_SUCCESS && nDeviceStatus == 1)
    {
        if (FObj)
        {
            Caption = FObj->VMS_CTLR_ID + ": " + FObj->VMS_NM;

            String sId   = FObj->VMS_CTLR_ID;
            String sName = FObj->VMS_NM;
            String sCaption;
            sCaption = sName;

            XnsSdkWindow1->SetOSDOnOff(OSD_ALL, false);
            XnsSdkWindow1->SetOSDOnOff(OSD_TIME1|OSD_IPS, true);

            XnsSdkWindow1->SetCustomOSDOnOff(false);
            WideString sOsdText = sCaption;
            XnsSdkWindow1->SetCustomOSD(sOsdText.Detach(), 1, 1, 255,255,255);
            XnsSdkWindow1->SetCustomOSDOnOff(true);

            XnsSdkWindow1->SetOSDOnOff(OSD_TIME1|OSD_IPS, true);
        }
        OpenWebCamera();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVmsCamOld::RefreshVms()
{
    FDispBlob = false;
}
//---------------------------------------------------------------------------

