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

#include <vcl.h>
#pragma hdrstop

#include "XnsCommon.h"
#include "XnsDeviceInterface.h"
#include "FrmSamsungPlayer1F.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "XNSSDKWINDOWLib_OCX"
#pragma link "XNSSDKDEVICELib_OCX"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "dxSkinBlack"
#pragma link "dxSkinMcSkin"
#pragma link "dxSkinsCore"
#pragma resource "*.dfm"

//TFrmSamsungPlayer1 *FrmSamsungPlayer1 = NULL;

//---------------------------------------------------------------------------
__fastcall TFrmSamsungPlayer1::TFrmSamsungPlayer1(TComponent* Owner, TWinControl* AParent)
    : TForm(Owner)
{
    Parent = AParent;
    Align  = alClient;

    Application->ProcessMessages();

    //::CoInitialize(NULL);

    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;

    FInitialize = false;
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmSamsungPlayer1::TmrShowTimer(TObject *Sender)
{
    TmrShow->Enabled = false;
#if 0
    Caption = FId + ": " + FLoc;
    WebCamPlay();
    SetFocus();
#endif
}
//---------------------------------------------------------------------------

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

void __fastcall TFrmSamsungPlayer1::FormDestroy(TObject *Sender)
{
    CommClose();
}
//---------------------------------------------------------------------------

void __fastcall TFrmSamsungPlayer1::CommClose()
{
    try {
        WebCamStop();
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmSamsungPlayer1::WebCamPlay()
{
    try
    {
        //LblErrMsg->Visible = false;
        Caption = FId + ": " + FLoc;
        //if (!FInitialize)
        {
            //SetupWebCamera();
        }
        //WebCamStop();
        // 신규 영상 연결
        ConnectWebCamera();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

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

bool __fastcall TFrmSamsungPlayer1::SetupWebCamera()
{
    String sErrMsg;
	long nRet = XnsSdkDevice1->Initialize();
	if (nRet != ERR_SUCCESS && nRet != ERR_ALREADY_INITIALIZE)
	{
    	sErrMsg.printf(L"Samsung XnsSdkDevice Initialize() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        //Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        ErrorMsg(sErrMsg);
        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() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        //Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        ErrorMsg(sErrMsg);
        return false;
	}

	m_lDeviceId = XnsSdkDevice1->CreateDeviceEx();
	//m_lDeviceId = XnsSdkDevice1->CreateDevice(1);
	m_hDevice = XnsSdkDevice1->GetDeviceHandle(m_lDeviceId);
	//m_hDevice = XnsSdkDevice1->CreateDevice(1);
	if (m_hDevice == 0)
	{
		sErrMsg = "CreateDevice() failed.";
    	sErrMsg.printf(L"Samsung XnsSdkWindow Initialize() failed.\r\nreturn=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        //Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        ErrorMsg(sErrMsg);
        return false;
	}

    FInitialize = true;
    return true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmSamsungPlayer1::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 TFrmSamsungPlayer1::ConnectWebCamera()
{
    bool bConnect = true;

	XnsSdkDevice1->SetConnectionInfo(
		m_hDevice,					            // [in] Device handle
		FDefModel.Detach(),				        // [in] Fixed as 'Samsung'
		FModelName.Detach(),				    // [in] Name of model to connect to. The maximum length allowed is 126-byte.
		XADDRESS_IP, FIpAddress.Detach(),	    // [in] Address type, actual address according to addresstype.
		FPort, 0,					            // [in] Port number, port number for web access
		FConnId.Detach(), FConnPass.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() failed.\r\nerrno=[%d](%s)\n", nRet, XnsSdkDevice1->GetErrorString(nRet));
        //Application->MessageBox(sErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
        ErrorMsg(sErrMsg);
        bConnect = false;
	}

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

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

    m_nControlId = 3;
    m_bIsMediaPlay = true;

    //XnsSdkWindow1->Visible = true;

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

void __fastcall TFrmSamsungPlayer1::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 TFrmSamsungPlayer1::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 TFrmSamsungPlayer1::XnsSdkDevice1ConnectFailed(TObject *Sender, long nDeviceID, long nControlID)
{
    Caption = Caption + " - Connect Failed.";
    ErrorMsg(Caption);
}
//---------------------------------------------------------------------------

void __fastcall TFrmSamsungPlayer1::XnsSdkDevice1DeviceStatusChanged(TObject *Sender, long nDeviceID, long nErrorCode, long nDeviceStatus,
          long nHddCondition)
{
	if (nErrorCode != ERR_SUCCESS || nDeviceStatus != 1)
	{
        ErrorMsg("Device Status Change");
		return;
	}

    //if (nErrorCode == ERR_SUCCESS && nDeviceStatus == 1)
    {
        Caption = FId + ": " + FLoc;

        String sId   = FId;
        String sName = FLoc;

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

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

        XnsSdkWindow1->SetOSDOnOff(OSD_TIME1|OSD_IPS, true);
#endif

        OpenWebCamera();
    }
}
//---------------------------------------------------------------------------

int __fastcall TFrmSamsungPlayer1::CameraControl(int ACommand, int ASpeed)
{
	long ret = -1;

    if (m_hDevice == 0 || m_nControlId == 0) return ret;

    int nPtzSpeed = ASpeed;

// 	if( nCommand != XPTZ_STOP)
// 		m_ctrlXnsDevice.ControlPtz(m_hDevice, m_nControlId, XPTZ_STOP, 30);

	// Returns the capabilities of the control module.
	long bIsCap = XnsSdkDevice1->GetControlCapability(m_hDevice, m_nControlId, XCTL_CAP_PTZ_SPEED);

	// [ XNS ACTIVEX HELP ]
	// -----------------------------------------------------------------------
	// Moves the camera to the predefined PTZ position. This function is
	// valid as long as the application is receiving media stream from the
	// camera.
	// -----------------------------------------------------------------------
	//	Command			Value	Description
	// -----------------------------------------------------------------------
	//	XPTZ_UP			1		Tilt up
	//	XPTZ_DOWN		2		Tilt down
	//	XPTZ_LEFT		3		Pan left
	//	XPTZ_RIGHT		4		Pan right
	//	XPTZ_UPLEFT		5		Tilt up and pan left
	//	XPTZ_UPRIGHT	6		Tilt up and pan right
	//	XPTZ_DOWNLEFT	7		Tilt down and pan left
	//	XPTZ_DOWNRIGHT	8		Tilt down and pan right
	//	XPTZ_ZOOMIN		9		Zoom in
	//	XPTZ_ZOOMOUT	10		Zoom out
	//	XPTZ_STOP		11		Stop the PTZ moving
	//	XPTZ_FOCUS_NEAR	12		Focus near
	//	XPTZ_FOCUS_FAR	13		Focus far
	//	XPTZ_FOCUS_STOP	14		Stop focus moving
	//	XPTZ_IRIS_OPEN	15		Open iris
	//	XPTZ_IRIS_CLOSE	16		Close iris
	// -----------------------------------------------------------------------
	if (bIsCap)
	{
		ret = XnsSdkDevice1->ControlPtz(
			m_hDevice,		// [in] Device handle. This value is returned from CreateDevice().
			m_nControlId,	// [in] Control ID.
			ACommand,		// [in] PTZ command
			nPtzSpeed		// [in] If nPtzCommand is a speed-related command,
							// this value indicates the PTZ operation speed.
							// (1~100) This value is valid only if the camera
							// supports the XCTL_CAP_PTZ_SPEED capability.
			);
	}
	else
    {
		ret = XnsSdkDevice1->ControlPtz(m_hDevice, m_nControlId, ACommand, 30);
    }

	if (ret != ERR_SUCCESS)
	{
        String sErr;
		sErr.printf(L"ControlPtz() fail:: error=[%d](%s)", ret, XnsSdkDevice1->GetErrorString(ret));
        ErrorMsg(sErr);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmSamsungPlayer1::ErrorMsg(String AErrMsg)
{
    LblErrMsg->Caption = AErrMsg;
    LblErrMsg->BringToFront();
    LblErrMsg->Transparent = true;
    LblErrMsg->Style->Font->Color = clWhite;
    LblErrMsg->Style->TextColor = clWhite;
    LblErrMsg->Visible = true;
    //Application->MessageBox(AErrMsg.c_str(), Caption.c_str(), MB_OK|MB_ICONERROR|MB_APPLMODAL);
}
//---------------------------------------------------------------------------

