// Sample08_StreamingDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Sample08_Streaming.h"
#include "Sample08_StreamingDlg.h"

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

/////////////////////////////////////////////////////////////////////////////
// CSample08_StreamingDlg dialog

CSample08_StreamingDlg::CSample08_StreamingDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSample08_StreamingDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSample08_StreamingDlg)
		// 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 CSample08_StreamingDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSample08_StreamingDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSample08_StreamingDlg, CDialog)
	//{{AFX_MSG_MAP(CSample08_StreamingDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_CRYPT, OnCrypt)
	ON_BN_CLICKED(ID_PLAY, OnPlay)
	ON_BN_CLICKED(ID_SITE, OnSite)
	ON_BN_CLICKED(ID_ORDER, OnOrder)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSample08_StreamingDlg message handlers

BOOL CSample08_StreamingDlg::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

	// FlashPlayerControl 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_VISIBLE | WS_CLIPSIBLINGS, 
						 rc.left, 
						 rc.top, 
						 rc.right - rc.left, 
						 rc.bottom - rc.top, 
						 m_hWnd, 
						 NULL, 
						 NULL, 
						 NULL);
	}

	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 CSample08_StreamingDlg::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 CSample08_StreamingDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

struct SThreadData
{
	IStream* m_pStreamForMarshalling;
	LPTSTR m_lpszCryptedFlashFilePath;

	static SThreadData* Alloc(IStream* pStreamForMarshalling, LPCTSTR lpszCryptedFlashFilePath)
	{
		SThreadData* pThreadData = (SThreadData*)CoTaskMemAlloc(sizeof(SThreadData));

		pThreadData->m_pStreamForMarshalling = pStreamForMarshalling;

		pThreadData->m_lpszCryptedFlashFilePath = 
			(TCHAR*)CoTaskMemAlloc(sizeof(TCHAR) * (1 + lstrlen(lpszCryptedFlashFilePath)));
		lstrcpy(pThreadData->m_lpszCryptedFlashFilePath, lpszCryptedFlashFilePath);

		return pThreadData;
	}

	static void Free(SThreadData* pThreadData)
	{
		CoTaskMemFree(pThreadData->m_lpszCryptedFlashFilePath);
		CoTaskMemFree(pThreadData);
	}
};

static DWORD WINAPI FlashContentProviderThread(LPVOID lpParameter);

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

	if (0 == lstrcmpi(lpszURL, _T("http://FLV/FlashVideo.flv")))
	{
		IStream* pStream = *ppStream;

		IStream* pStreamForMarshalling;
		CoMarshalInterThreadInterfaceInStream(IID_IStream, pStream, &pStreamForMarshalling);

		SThreadData* pThreadData = SThreadData::Alloc(pStreamForMarshalling, m_strCryptedFlashFilePath);
		
		DWORD dwThreadId;
		HANDLE hThread = CreateThread(NULL, 0, &FlashContentProviderThread, pThreadData, 0, &dwThreadId);
		CloseHandle(hThread);

		return S_ASYNCHRONOUS;
	}

	return hr;
}

DWORD WINAPI FlashContentProviderThread(LPVOID lpParameter)
{
	CoInitialize(NULL);

	SThreadData* pThreadData = (SThreadData*)lpParameter;

	IStream* pStream;
	CoUnmarshalInterface(pThreadData->m_pStreamForMarshalling, IID_IStream, (void**)&pStream);

	HANDLE hFile = CreateFile(pThreadData->m_lpszCryptedFlashFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	char Buffer[1024];

	while (true)
	{
		DWORD nRead = 0;
		BOOL bRes = ReadFile(hFile, Buffer, sizeof(Buffer), &nRead, NULL);

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

		// Decrypt
		for (DWORD i = 0; i < nRead; i++)
			Buffer[i] ^= 0x06;

		DWORD nWritten = 0;

		if (S_OK != pStream->Write(Buffer, nRead, &nWritten))
			break;
	}

	CloseHandle(hFile);

	pThreadData->m_pStreamForMarshalling->Release();
	pStream->Release();

	SThreadData::Free(pThreadData);

	CoUninitialize();

	return 1;
}

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

	FPC_RemoveOnLoadExternalResourceHandler(theApp.m_hFPC, m_dwHandlerCookie);
}

void CSample08_StreamingDlg::OnCrypt() 
{
	AfxMessageBox(_T("Select flash movie or flash video file for crypting"));

	CString strInputFile;
	{
		CFileDialog dlg(TRUE, 
						_T("swf"), 
						_T(""), 
						0, 
						_T("Flash files (*.swf;*.flv)|*.swf;*.flv|All Files (*.*)|*.*||"), 
						this);

		if (IDOK == dlg.DoModal())
			strInputFile = dlg.GetPathName();
		else
			return;
	}

	AfxMessageBox(_T("Select where to save a crypted file"));

	CString strOutputFile;
	{
		CFileDialog dlg(FALSE, 
						_T("crypted"), 
						strInputFile + _T(".crypted"), 
						OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, 
						_T("Crypted Flash files (*.crypted)|*.crypted;*.crypted|All Files (*.*)|*.*||"), 
						this);

		if (IDOK == dlg.DoModal())
			strOutputFile = dlg.GetPathName();
		else
			return;
	}

	if (IDOK != 
		AfxMessageBox(_T("This is a demo application. That's why the crypting is very simple (XOR)\nPress OK to start"), MB_OKCANCEL))
		return;

	HANDLE hFile__Input = CreateFile(strInputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
	HANDLE hFile__Output = CreateFile(strOutputFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);

	char Buffer[1024];
	BOOL bRes;
	DWORD dwNumberOfBytesRead, dwNumberOfBytesWritten;

	while (true)
	{
		bRes = ReadFile(hFile__Input, Buffer, sizeof(Buffer), &dwNumberOfBytesRead, NULL);

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

		// Very-very simple crypting
		for (DWORD i = 0; i < dwNumberOfBytesRead; i++)
			Buffer[i] ^= 0x06;

		WriteFile(hFile__Output, Buffer, dwNumberOfBytesRead, &dwNumberOfBytesWritten, NULL);
	}

	CloseHandle(hFile__Input);
	CloseHandle(hFile__Output);

	if (IDYES == 
		AfxMessageBox(_T("The crypting finished.\nWould you like to open the crypted file and play it?"), MB_YESNO | MB_DEFBUTTON1))
		PlayCryptedFlashFile(strOutputFile);
}

void CSample08_StreamingDlg::OnPlay() 
{
	CFileDialog dlg(TRUE, 
					_T("crypted"), 
					_T(""), 
					0, 
					_T("Crypted Flash files (*.crypted)|*.crypted|All Files (*.*)|*.*||"), 
					this);

	if (IDOK == dlg.DoModal())
		PlayCryptedFlashFile(dlg.GetPathName());
}

void CSample08_StreamingDlg::PlayCryptedFlashFile(LPCTSTR lpszPath)
{
	// Read and decrypt first three bytes to determinate the type of this file (flash movie or flash video)
	HANDLE hFile = CreateFile(lpszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	char Buffer[3] = { 0 };
	DWORD dwNumberOfBytesRead;

	ReadFile(hFile, Buffer, sizeof(Buffer), &dwNumberOfBytesRead, NULL);

	CloseHandle(hFile);

	// Decrypt
	for (int i = 0; i < sizeof(Buffer); i++)
		Buffer[i] ^= 0x06;

	m_strCryptedFlashFilePath = lpszPath;

	if ('F' == Buffer[0] && 'L' == Buffer[1] && 'V' == Buffer[2])
	{
		FPC_PutFlashVars(m_hwndFlashPlayerControl, _T("FLVPath=http://FLV/FlashVideo.flv"));

		// Flash video
		FPCPutMovieFromResource(m_hwndFlashPlayerControl, NULL, _T("FLVPLAYER"), _T("SWF"));
	}
	else
		// Flash movie
	{
		IStream* pStream;
		FPCPutMovieUsingStream(m_hwndFlashPlayerControl, &pStream);

		IStream* pStreamForMarshalling;
		CoMarshalInterThreadInterfaceInStream(IID_IStream, pStream, &pStreamForMarshalling);

		pStream->Release();
		pStream = NULL;

		SThreadData* pThreadData = SThreadData::Alloc(pStreamForMarshalling, m_strCryptedFlashFilePath);

		DWORD dwThreadId;
		HANDLE hThread = CreateThread(NULL, 0, &FlashContentProviderThread, pThreadData, 0, &dwThreadId);
		CloseHandle(hThread);
	}
}

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

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