// Sample01_SWF_And_FLV_PlayerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Sample01_SWF_And_FLV_Player.h"
#include "Sample01_SWF_And_FLV_PlayerDlg.h"
#include "URLDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSample01_SWF_And_FLV_PlayerDlg dialog

CSample01_SWF_And_FLV_PlayerDlg::CSample01_SWF_And_FLV_PlayerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSample01_SWF_And_FLV_PlayerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSample01_SWF_And_FLV_PlayerDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSample01_SWF_And_FLV_PlayerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSample01_SWF_And_FLV_PlayerDlg)
	DDX_Control(pDX, IDC_SLIDER_SOUND_VOLUME, m_wndSliderCtrl__SoundVolume);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSample01_SWF_And_FLV_PlayerDlg, CDialog)
	//{{AFX_MSG_MAP(CSample01_SWF_And_FLV_PlayerDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_CHECK_STANDARD_MENU, OnCheckStandardMenu)
	ON_BN_CLICKED(ID_PLAY_SWF_FLV_FROM_FILE, OnPlaySwfFlvFromFile)
	ON_BN_CLICKED(IDC_CHECK_SOUNDS, OnCheckSounds)
	ON_BN_CLICKED(ID_SITE, OnSite)
	ON_BN_CLICKED(ID_ORDER, OnOrder)
	ON_WM_HSCROLL()
	ON_BN_CLICKED(ID_PLAY_SWF_FLV_FROM_URL, OnPlaySwfFlvFromUrl)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSample01_SWF_And_FLV_PlayerDlg message handlers

BOOL CSample01_SWF_And_FLV_PlayerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	// f_in_box creating
	// NOTE: CALL FPC_LoadRegisteredOCX() or FPC_LoadOCXCodeFromMemory() before creating!
	// See InitInstance() implementation
	{
		RECT rc;
		GetDlgItem(IDC_STATIC_FPC_PLACE)->GetWindowRect(&rc);
		ScreenToClient(&rc);

		m_hwndFlashPlayerControl = 
			CreateWindow((LPCTSTR)FPC_GetClassAtom(theApp.m_hFPC), 
						 NULL, 
						 WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, 
						 rc.left, 
						 rc.top, 
						 rc.right - rc.left, 
						 rc.bottom - rc.top, 
						 m_hWnd, 
						 NULL, 
						 NULL, 
						 NULL);
	}

	// Loading movie from file
	{
		TCHAR lpszMoviePath[_MAX_PATH + 1] = { 0 };
		GetModuleFileName(NULL, lpszMoviePath, _MAX_PATH);

		int nIndex;
		
		for (nIndex = lstrlen(lpszMoviePath) - 1; nIndex >= 0; nIndex--)
			if (_T('\\') == lpszMoviePath[nIndex])
			{
				lpszMoviePath[nIndex] = 0;
				break;
			}
		lstrcat(lpszMoviePath, _T("\\movie.swf"));

		SFPCPutMovie FPCPutMovie;
        FPCPutMovie.lpszBuffer = lpszMoviePath;
		::SendMessage(m_hwndFlashPlayerControl, FPCM_PUT_MOVIE, 0, (LPARAM)&FPCPutMovie);

		FPC_Play(m_hwndFlashPlayerControl);
	}

	m_wndSliderCtrl__SoundVolume.SetRange(0, 100);

	CheckDlgButton(IDC_CHECK_SOUNDS, BST_CHECKED);
	OnCheckSounds();

	m_dwHandlerCookie = FPC_AddOnLoadExternalResourceHandler(theApp.m_hFPC, &StaticGlobalOnLoadExternalResourceHandler, (LPARAM)this);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSample01_SWF_And_FLV_PlayerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSample01_SWF_And_FLV_PlayerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

HRESULT WINAPI CSample01_SWF_And_FLV_PlayerDlg::GlobalOnLoadExternalResourceHandler(LPCTSTR lpszURL, IStream** ppStream, HFPC hFPC)
{
	HRESULT hr = E_FAIL;

	if (0 == lstrcmpi(lpszURL, _T("http://FLV/FlashVideo.flv")))
	{
		IStream* pMemStream = NULL;
		CreateStreamOnHGlobal(NULL, TRUE, &pMemStream);
		
		HANDLE hFile = CreateFile(m_strFLVPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

		if (INVALID_HANDLE_VALUE != hFile)
		{
			const DWORD nBufferSize = 1024 * 1024;
			BYTE* pBuffer = new BYTE[nBufferSize];
			DWORD dwNumberOfBytesRead;
			ULONG nWritten;

			while (true)
			{
				BOOL bRes = ReadFile(hFile, pBuffer, nBufferSize, &dwNumberOfBytesRead, NULL);

				if (!bRes || 0 == dwNumberOfBytesRead)
					break;

				pMemStream->Write(pBuffer, dwNumberOfBytesRead, &nWritten);
			}

			delete[] pBuffer;

			CloseHandle(hFile);

			LARGE_INTEGER liZero = { 0 };
			ULARGE_INTEGER ulNewPosition;
			pMemStream->Seek(liZero, STREAM_SEEK_SET, &ulNewPosition);

			*ppStream = pMemStream;
			hr = S_OK;
		}
	}

	return hr;
}

void CSample01_SWF_And_FLV_PlayerDlg::OnCheckStandardMenu() 
{
	SFPCPutStandardMenu FPCPutStandardMenu;
	FPCPutStandardMenu.StandardMenu = IsDlgButtonChecked(IDC_CHECK_STANDARD_MENU);
	::SendMessage(m_hwndFlashPlayerControl, FPCM_PUT_STANDARD_MENU, 0, (LPARAM)&FPCPutStandardMenu);
}

void CSample01_SWF_And_FLV_PlayerDlg::OnPlaySwfFlvFromFile() 
{
    CFileDialog dlg(TRUE, 
                    _T("swf"), 
                    _T(""), 
                    0, 
                    _T("All Flash Files (*.swf;*.flv)|*.swf;*.flv|Flash Movies (*.swf)|*.swf|Flash Video Files (*.flv)|*.flv|All Files (*.*)|*.*||"), 
                    this);

    if (IDOK == dlg.DoModal())
    {
        //
        CString strFlashMoviePath = dlg.GetPathName();

		if (0 == dlg.GetFileExt().CompareNoCase(_T("swf")))
		{
			//
			TCHAR lpszFlashMoviePath[MAX_PATH + 1] = { 0 };
			lstrcpy(lpszFlashMoviePath, strFlashMoviePath);

			//
			SFPCPutMovie SFPCPutMovie;
			SFPCPutMovie.lpszBuffer = lpszFlashMoviePath;
			::SendMessage(m_hwndFlashPlayerControl, FPCM_PUT_MOVIE, 0, (LPARAM)&SFPCPutMovie);
		}
		else
		{
			// First way -- provide FLV content using GlobalOnLoadExternalResourceHandler
			// Additionally, see Sample02_SWF_FLV_Embedding
			// This way is useful when you provide FLV from memory, stream, database and so on
			// When you should play FLV from URL / local file, use the Second way (see below)
			/*
				m_strFLVPath = strFlashMoviePath;

				FPC_PutFlashVars(m_hwndFlashPlayerControl, _T("FLVPath=http://FLV/FlashVideo.flv"));
				FPCPutMovieFromResource(m_hwndFlashPlayerControl, 0, _T("FLVPlayer"), _T("SWF"));
			*/

			// Second way -- just provide URL for Flash
			CString strFlashVars = _T("FLVPath=");
			strFlashVars += strFlashMoviePath;
			FPC_PutFlashVars(m_hwndFlashPlayerControl, strFlashVars);
			FPCPutMovieFromResource(m_hwndFlashPlayerControl, 0, _T("FLVPlayer"), _T("SWF"));
		}
    }
}

void CSample01_SWF_And_FLV_PlayerDlg::OnCheckSounds() 
{
	BOOL bEnableSound = IsDlgButtonChecked(IDC_CHECK_SOUNDS);

	FPC_EnableSound(theApp.m_hFPC, bEnableSound);

	m_wndSliderCtrl__SoundVolume.EnableWindow(bEnableSound);

	if (bEnableSound)
	{
		CString str;
		str.Format(_T("%d %%"), FPC_GetSoundVolume(theApp.m_hFPC) * 100 / DEF_MAX_FLASH_AUDIO_VOLUME);

		GetDlgItem(IDC_STATIC_VOLUME)->SetWindowText(str);
	}
	else
		GetDlgItem(IDC_STATIC_VOLUME)->SetWindowText(_T("disabled"));

	m_wndSliderCtrl__SoundVolume.SetPos(FPC_GetSoundVolume(theApp.m_hFPC) * m_wndSliderCtrl__SoundVolume.GetRangeMax() / DEF_MAX_FLASH_AUDIO_VOLUME);
}

void CSample01_SWF_And_FLV_PlayerDlg::PostNcDestroy() 
{
	CDialog::PostNcDestroy();

	FPC_RemoveOnLoadExternalResourceHandler(theApp.m_hFPC, m_dwHandlerCookie);
}

void CSample01_SWF_And_FLV_PlayerDlg::OnSite() 
{
	ShellExecute(m_hWnd, NULL, _T("http://www.f-in-box.com/dll/"), NULL, NULL, SW_SHOW);
}

void CSample01_SWF_And_FLV_PlayerDlg::OnOrder() 
{
	ShellExecute(m_hWnd, NULL, _T("http://www.f-in-box.com/dll/order.html"), NULL, NULL, SW_SHOW);
}

void CSample01_SWF_And_FLV_PlayerDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) 
{
	FPC_SetSoundVolume(theApp.m_hFPC, m_wndSliderCtrl__SoundVolume.GetPos() * DEF_MAX_FLASH_AUDIO_VOLUME / m_wndSliderCtrl__SoundVolume.GetRangeMax());

	BOOL bEnableSound = IsDlgButtonChecked(IDC_CHECK_SOUNDS);

	if (bEnableSound)
	{
		CString str;
		str.Format(_T("%d %%"), FPC_GetSoundVolume(theApp.m_hFPC) * 100 / DEF_MAX_FLASH_AUDIO_VOLUME);

		GetDlgItem(IDC_STATIC_VOLUME)->SetWindowText(str);
	}
	else
		GetDlgItem(IDC_STATIC_VOLUME)->SetWindowText(_T("disabled"));
	
	CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
}

void CSample01_SWF_And_FLV_PlayerDlg::OnPlaySwfFlvFromUrl() 
{
	CURLDlg dlg;

	if (IDOK == dlg.DoModal())
	{
		if (dlg.m_bIsSWF)
		{
			//
			SFPCPutMovie SFPCPutMovie;
			SFPCPutMovie.lpszBuffer = dlg.m_strURL.GetBuffer(dlg.m_strURL.GetLength() + 1);
			::SendMessage(m_hwndFlashPlayerControl, FPCM_PUT_MOVIE, 0, (LPARAM)&SFPCPutMovie);
			dlg.m_strURL.ReleaseBuffer();
		}
		else
		{
			// Just provide URL for Flash
			CString strFlashVars = _T("FLVPath=");
			// Note that you should URLEncode dlg.m_strURL, here we don't URLEncode, 
			// but you should
			strFlashVars += dlg.m_strURL;
			FPC_PutFlashVars(m_hwndFlashPlayerControl, strFlashVars);
			FPCPutMovieFromResource(m_hwndFlashPlayerControl, 0, _T("FLVPlayer"), _T("SWF"));
		}
	}
}
