/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is 
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or 
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the NPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the NPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <gpac/m4_terminal.h>

#include <windows.h>
#include <windowsx.h>

#include "plugin.h"

//////////////////////////////////////
//
// general initialization and shutdown
//
NPError NS_PluginInitialize()
{
  return NPERR_NO_ERROR;
}

void NS_PluginShutdown()
{
}

/////////////////////////////////////////////////////////////
//
// construction and destruction of our plugin instance object
//
nsPluginInstanceBase * NS_NewPluginInstance(nsPluginCreateData * aCreateDataStruct)
{
  if(!aCreateDataStruct)
    return NULL;

  nsPluginInstance * plugin = new nsPluginInstance(aCreateDataStruct->instance);
  return plugin;
}

void NS_DestroyPluginInstance(nsPluginInstanceBase * aPlugin)
{
  if(aPlugin)
    delete (nsPluginInstance *)aPlugin;
}

////////////////////////////////////////
//
// nsPluginInstance class implementation
//
nsPluginInstance::nsPluginInstance(NPP aInstance) : nsPluginInstanceBase(),
  mInstance(aInstance),
  mInitialized(FALSE)
{
  mhWnd = NULL;
}

nsPluginInstance::~nsPluginInstance()
{
}

/*static LRESULT CALLBACK PluginWinProc(HWND, UINT, WPARAM, LPARAM);
static WNDPROC lpOldProc = NULL;*/

NPBool nsPluginInstance::init(NPWindow* aWindow)
{
	if(aWindow == NULL)
    return FALSE;

	mhWnd = (HWND)aWindow->window;
	if(mhWnd == NULL)
	return FALSE;

	// subclass window so we can intercept window messages and
	// do our drawing to it
	/*lpOldProc = SubclassWindow(mhWnd, (WNDPROC)PluginWinProc);*/

	// associate window with our nsPluginInstance object so we can access 
	// it in the window procedure
	SetWindowLong(mhWnd, GWL_USERDATA, (LONG)this);

	assert(1);
	unsigned char config_path[MAX_PATH];
#ifdef _DEBUG
	strcpy((char *) config_path, "C:\\Users\\Cyril\\sourceforge\\gpac-0.2.0\\gpac\\bin\\Debug\\");
#else
	strcpy((char *) config_path, "C:\\Users\\Cyril\\sourceforge\\gpac-0.2.0\\gpac\\bin\\Release\\");
#endif

	/*init config and plugins*/
	m_config = NewIniFile((const char *) config_path, "GPAC.cfg");
	if (!m_config) {
		/*create blank config file in the exe dir*/
		unsigned char config_file[MAX_PATH];
		strcpy((char *) config_file, (const char *) config_path);
		strcat((char *) config_file, "GPAC.cfg");
		FILE *ft = fopen((const char *) config_file, "wt");
		fclose(ft);
		m_config = NewIniFile((const char *) config_path, "GPAC.cfg");
		if (!m_config) {
			MessageBox(NULL, "GPAC Configuration file not found", "Fatal Error", MB_OK);
			return FALSE;
		}
	}

	m_config_dir = (unsigned char *)malloc(strlen((const char *)config_path));
	strcpy((char *)m_config_dir,(const char *)config_path);

	char *str = IF_GetKey(m_config, "General", "PluginsDirectory");
	m_plugins = NewPluginManager((const unsigned char *) str, m_config);
	if (!m_plugins) {
		char *sOpt;
		/*inital launch*/
		m_plugins = NewPluginManager((const unsigned char *) config_path, m_config);
		if (m_plugins) {
			IF_SetKey(m_config, "General", "PluginsDirectory", (const char *) config_path);

			sOpt = IF_GetKey(m_config, "Rendering", "DriverName");
			if (!sOpt) IF_SetKey(m_config, "Rendering", "DriverName", "gdip_rend");

			sOpt = IF_GetKey(m_config, "General", "CacheDirectory");
			if (!sOpt) {
				unsigned char str_path[MAX_PATH];
				sprintf((char *) str_path, "%scache", config_path);
				IF_SetKey(m_config, "General", "CacheDirectory", (const char *) str_path);
			}
			/*setup UDP traffic autodetect*/
			IF_SetKey(m_config, "Network", "AutoReconfigUDP", "yes");
			IF_SetKey(m_config, "Network", "UDPNotAvailable", "no");
			IF_SetKey(m_config, "Network", "UDPTimeout", "10000");
			IF_SetKey(m_config, "Network", "BufferLength", "3000");
		}

		/*check audio config on windows, force config*/
		sOpt = IF_GetKey(m_config, "Audio", "ForceConfig");
		if (!sOpt) {
			IF_SetKey(m_config, "Audio", "ForceConfig", "yes");
			IF_SetKey(m_config, "Audio", "NumBuffers", "8");
			IF_SetKey(m_config, "Audio", "BuffersPerSecond", "16");
		}
		/*by default use GDIplus, much faster than freetype on font loading*/
		IF_SetKey(m_config, "FontEngine", "DriverName", "gdip_rend");

	}	
	if (! PM_GetPluginsCount(m_plugins) ) {
		MessageBox(NULL, "No plugins available - system cannot work", "Fatal Error", MB_OK);
		return FALSE;
	}

	/*setup font dir*/
	str = IF_GetKey(m_config, "FontEngine", "FontDirectory");
	if (!str) {
		::GetWindowsDirectory((char*)config_path, MAX_PATH);
		if (config_path[strlen((char*)config_path)-1] != '\\') strcat((char*)config_path, "\\");
		strcat((char *)config_path, "Fonts");
		IF_SetKey(m_config, "FontEngine", "FontDirectory", (const char *) config_path);
	}

	/*check video driver, if none or raw_out use dx_hw by default*/
	str = IF_GetKey(m_config, "Video", "DriverName");
	if (!str || !stricmp(str, "raw_out")) {
		IF_SetKey(m_config, "Video", "DriverName", "dx_hw");
	}

	mInitialized = TRUE;
  return TRUE;
}

void nsPluginInstance::shut()
{
  // subclass it back
/*  SubclassWindow(mhWnd, lpOldProc);*/
  free(m_config_dir);
  free(m_filename);
  mhWnd = NULL;
  mInitialized = FALSE;
}

NPBool nsPluginInstance::isInitialized()
{
  return mInitialized;
}

const char * nsPluginInstance::getVersion()
{
  return NPN_UserAgent(mInstance);
}

Bool Osmozilla_EventProc(void *priv, M4Event *evt)
{
	u32 dur;
	nsPluginInstance *gpac = (nsPluginInstance *) priv;

	return 0;
}


/*
static LRESULT CALLBACK PluginWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch (msg) {
    case WM_PAINT:
      {
        // draw a frame and display the string
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);
        RECT rc;
        GetClientRect(hWnd, &rc);
        FrameRect(hdc, &rc, GetStockBrush(BLACK_BRUSH));

        // get our plugin instance object and ask it for the version string
        nsPluginInstance *plugin = (nsPluginInstance *)GetWindowLong(hWnd, GWL_USERDATA);
        if (plugin) {
          const char * string = "Osmozilla soon";//plugin->getVersion();
          DrawText(hdc, string, strlen(string), &rc, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        }
        else {
          char string[] = "Error occured";
          DrawText(hdc, string, strlen(string), &rc, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        }

        EndPaint(hWnd, &ps);
      }
      break;
    default:
      break;
  }

  return DefWindowProc(hWnd, msg, wParam, lParam);
}
*/

NPError nsPluginInstance::SetWindow(NPWindow* pNPWindow)                    
{ 
	HWND hWnd = (HWND__ *)pNPWindow->window;
	memset(&m_user, 0, sizeof(M4User));
	m_user.config = m_config;
	m_user.plugins = m_plugins;
	m_user.opaque = this;
	m_user.os_window_handler = hWnd;
	m_user.EventProc = Osmozilla_EventProc;

	m_prev_time = 0;
	m_term = NewMPEG4Term(&m_user);
	if (! m_term) {
		MessageBox(NULL, "Cannot load MPEG-4 Terminal", "Fatal Error", MB_OK);
		return NPERR_GENERIC_ERROR;
	}

	SetOptions();

	m_url_changed = 0;
	if (1) {
		unsigned char url_path[MAX_PATH] = "C:\\Users\\Cyril\\sourceforge\\gpac_regression_tests-0.1.4\\GPAC_Regression_Tests\\03-Appearance\\MovieTexture\\Shapes\\scene.mp4";
		m_filename = (unsigned char *)malloc(strlen((const char *)url_path));
		strcpy((char *)m_filename,(const char *)url_path);
		m_url_changed = 1;
		M4_Sleep(1100);
		M4T_ConnectURL(m_term, (LPCSTR)m_filename);
		//hWnd->PostMessage(WM_OPENURL);
	}


	return NPERR_NO_ERROR; 
}

void nsPluginInstance::SetOptions()
{
	char *sOpt = IF_GetKey(m_config, "General", "Loop");
	if (sOpt && !stricmp(sOpt, "yes")) {
		m_Loop = 1;
	} else {
		m_Loop = 0;
	}
	sOpt = IF_GetKey(m_config, "General", "AutoStart");
	if (sOpt && !stricmp(sOpt, "no")) {
		m_AutoStart = 0;
	} else {
		m_AutoStart = 1;
	}
	sOpt = IF_GetKey(m_config, "General", "ConsoleOff");
	if (sOpt && !stricmp(sOpt, "yes")) {
		m_NoConsole = 1;
	} else {
		m_NoConsole = 0;
	}

	sOpt = IF_GetKey(m_config, "General", "ViewXMT");
	if (sOpt && !stricmp(sOpt, "yes")) {
		m_ViewXMTA = 1;
	} else {
		m_ViewXMTA = 0;
	}
	
}
