//====START_GENERATED_PROLOG======================================
//
//
//   COMPONENT_NAME: odother
//
//   CLASSES: none
//
//   ORIGINS: 27
//
//
//   (C) COPYRIGHT International Business Machines Corp. 1995,1996
//   All Rights Reserved
//   Licensed Materials - Property of IBM
//   US Government Users Restricted Rights - Use, duplication or
//   disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//
//   IBM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
//   ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//   PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
//   CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
//   USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
//   OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
//   OR PERFORMANCE OF THIS SOFTWARE.
//
//====END_GENERATED_PROLOG========================================
//
// @(#) 1.4 nt/src/samples/JavaPart/misc.cpp, odjavapart, od96nt, odnt9714c 3/19/97 03:59:37 [ 4/2/97 17:55:03 ]

#ifndef IBMSample_MISC
#include "Misc.h"
#endif

#ifndef IBMSample_HELP
#include "Help.h"
#endif

#ifndef IBMSample_JAVAPART
#include "IODJava.h"
#endif

extern "C" {
	#include <objbase.h>
	#include <winreg.h>
	#include <stdio.h>
	#include <stdlib.h>
}


/*
 *  Main registry key...
 */
static const char* kRegistry_JavaPart      = "Software\\IBM\\IBM JavaPart";

/*
 *  Proxy registry keys and default values...
 */
static const char* kRegistry_Proxy         = "Proxy Information";
static const char* kRegistry_ProxyHost     = "Proxy Host";
static const char* kRegistry_ProxyPort     = "Proxy Port";
static const char* kRegistry_ProxySet      = "Proxy Set";

static const char* kDefault_ProxyHost      = "proxy.austin.ibm.com";
static const char* kDefault_ProxyPort      = "80";
static const char* kDefault_ProxySet       = "true";

/*
 *  URL registry keys and default values...
 */
static const char* kRegistry_URL           = "Default URL";
static const char* kDefault_URL            = "file://";


/*-------------------------------------------------------------------+
|                       JavaPart::SetProxy ()                        |
| ================================================================== |
|                                                                    |
| Function:    Saves the proxy information (host, port) in the       |
|              Windows registry.                                     |
|                                                                    |
| Algorithm:   Creates/uses the following registry structure to save |
|              the proxy information:                                |
|                                                                    |
|              HKEY_CURRENT_USER                                     |
|                  Software                                          |
|                      IBM                                           |
|                          IBM JavaPart                              |
|                              Proxy Information                     |
|                                                                    |
| Parameters:  proxyHost - name of the proxy host                    |
|              proxyPort - corresponding proxy port                  |
|              proxySet  - whether or not to use a proxy             |
|                                                                    |
| Returns:     ERROR_SUCCESS upon successful completion.             |
|              Otherwise returns the error code.                     |
|                                                                    |
+-------------------------------------------------------------------*/
long SetProxy (const char* proxyHost, const char* proxyPort, const char* proxySet)
{
	HRESULT rc;

	HKEY hProxyKey;

	do {
		char keyStr [255];
		sprintf (keyStr, "%s\\%s", kRegistry_JavaPart, kRegistry_Proxy);

		/*
		 *  Open the key if it already exists, otherwise create it.
		 */
		rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
				   KEY_ALL_ACCESS, &hProxyKey);

		if (rc != ERROR_SUCCESS) {
			rc = RegCreateKey (HKEY_CURRENT_USER, keyStr, 
					   &hProxyKey);
		}
		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Save the proxy host...
		 */
		rc = RegSetValueEx (hProxyKey, kRegistry_ProxyHost, 0, 
				    REG_SZ, (const byte*) proxyHost,
				    strlen (proxyHost) + 1);
		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Save the proxy port...
		 */
		rc = RegSetValueEx (hProxyKey, kRegistry_ProxyPort, 0, 
				    REG_SZ, (const byte*) proxyPort,
				    strlen (proxyPort) + 1);
		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Save whether to use a proxy...
		 */
		rc = RegSetValueEx (hProxyKey, kRegistry_ProxySet, 0, 
				    REG_SZ, (const byte*) proxySet,
				    strlen (proxySet) + 1);

	} while (0);

	return rc;
}


/*-------------------------------------------------------------------+
|                       JavaPart::GetProxy ()                        |
| ================================================================== |
|                                                                    |
| Function:    Retrieves the proxy information (host, port) from the |
|              Windows registry.                                     |
|                                                                    |
| Algorithm:   Query the appropriate registry values (see SetProxy). |
|                                                                    |
| Parameters:  proxyHost - buffer for retrieved proxy host           |
|              proxyPort - buffer for retrieved proxy port           |
|              proxySet  - buffer for retrieved proxy set            |
|                                                                    |
| Returns:     ERROR_SUCCESS upon successful completion.             |
|              Otherwise returns the error code.                     |
|                                                                    |
+-------------------------------------------------------------------*/
long GetProxy (char* proxyHost, char* proxyPort, char* proxySet)
{
	HRESULT rc;

	HKEY hProxyKey;

	do {
		char keyStr [255];
		sprintf (keyStr, "%s\\%s", kRegistry_JavaPart, kRegistry_Proxy);

		/*
		 *  Open the proxy information registry key...
		 */
		rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
				   KEY_ALL_ACCESS, &hProxyKey);
		/*
		 *  Proxy information has not been stored in the registry
		 *  yet, so we'll store some default values and continue...
		 */
		if (rc != ERROR_SUCCESS) {

			SetProxy (kDefault_ProxyHost, kDefault_ProxyPort, kDefault_ProxySet);

			rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
					   KEY_ALL_ACCESS, &hProxyKey);
		}

		/*
		 *  Retrieve the proxy host information...
		 */
		DWORD type;
		DWORD length = 255;
		rc = RegQueryValueEx (hProxyKey, kRegistry_ProxyHost,
				      0, &type, (LPBYTE) proxyHost, &length);
		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Retrieve the proxy port information...
		 */
		length = 255;
		rc = RegQueryValueEx (hProxyKey, kRegistry_ProxyPort,
				      0, &type, (LPBYTE) proxyPort, &length);

		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Retrieve whether to use a proxy...
		 */
		length = 255;
		rc = RegQueryValueEx (hProxyKey, kRegistry_ProxySet,
				      0, &type, (LPBYTE) proxySet, &length);

		if (rc != ERROR_SUCCESS) strcpy(proxySet, kDefault_ProxySet);

		/*
		 *  Now close the registry keys...
		 */
		RegCloseKey (hProxyKey);

	} while (0);

	return rc;
}


/*-------------------------------------------------------------------+
|                    JavaPart::SetDefaultURL ()                      |
| ================================================================== |
|                                                                    |
| Function:    Saves the default URL in the Windows registry...      |
|                                                                    |
| Algorithm:   Creates/uses the following registry structure to save |
|              the proxy information:                                |
|                                                                    |
|              HKEY_CURRENT_USER                                     |
|                  Software                                          |
|                      IBM                                           |
|                          IBM JavaPart                              |
|                              Default URL                           |
|                                                                    |
| Parameters:  url - the default URL                                 |
|                                                                    |
| Returns:     ERROR_SUCCESS upon successful completion.             |
|              Otherwise returns the error code.                     |
|                                                                    |
+-------------------------------------------------------------------*/
long SetDefaultURL (const char* url)
{
	HRESULT rc;

	HKEY hUrlKey;

	do {
		char keyStr [255];
		sprintf (keyStr, "%s\\%s", kRegistry_JavaPart, kRegistry_URL);

		/*
		 *  Open the key if it already exists, otherwise create it.
		 */
		rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
				   KEY_ALL_ACCESS, &hUrlKey);

		if (rc != ERROR_SUCCESS) {
			rc = RegCreateKey (HKEY_CURRENT_USER, keyStr, 
					   &hUrlKey);
		}
		if (rc != ERROR_SUCCESS) break;

		/*
		 *  Save the default URL...
		 */
		rc = RegSetValueEx (hUrlKey, NULL, 0, 
				    REG_SZ, (const byte*) url,
				    strlen (url) + 1);
		if (rc != ERROR_SUCCESS) break;

	} while (0);

	return rc;
}


/*-------------------------------------------------------------------+
|                    JavaPart::GetDefaultURL ()                      |
| ================================================================== |
|                                                                    |
| Function:    Retrieves the default URL from the Windows registry.  |
|                                                                    |
| Algorithm:   Query the appropriate registry values (see            |
	       SetDefaultURL).                                       |
|                                                                    |
| Parameters:  url - the default URL                                 |
|                                                                    |
| Returns:     The URL upon successful completion.                   |
|              Otherwise returns NULL.                               |
|                                                                    |
+-------------------------------------------------------------------*/
char* GetDefaultURL ()
{
	static char url [255];
	HRESULT rc;

	HKEY hUrlKey;

	do {
		char keyStr [255];
		sprintf (keyStr, "%s\\%s", kRegistry_JavaPart, kRegistry_URL);

		/*
		 *  Open the default URL information registry key...
		 */
		rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
				   KEY_ALL_ACCESS, &hUrlKey);
		/*
		 *  URL information has not been stored in the registry
		 *  yet, so we'll store the default value and continue...
		 */
		if (rc != ERROR_SUCCESS) {

			char buffer [255];
			sprintf (buffer, "%s/%s/JavaPart.htm",
				kDefault_URL, GetSamplesPath ());
				
			SetDefaultURL (buffer);

			rc = RegOpenKeyEx (HKEY_CURRENT_USER, keyStr, 0, 
					   KEY_ALL_ACCESS, &hUrlKey);
		}

		/*
		 *  Retrieve the default URL information...
		 */
		DWORD type;
		DWORD length = 255;
		rc = RegQueryValueEx (hUrlKey, NULL, 0, &type, 
				      (LPBYTE) url, &length);
		/*
		 *  Now close the registry keys...
		 */
		RegCloseKey (hUrlKey);

	} while (0);

	if (rc == ERROR_SUCCESS)
		return url;
	else
		return NULL;
}


/*-------------------------------------------------------------------+
|                        CheckEnvironment ()                         |
| ================================================================== |
|                                                                    |
| Function:    Check to insure that the users environment is setup   |
|              correctly.  Checks the following:                     |
|                                                                    |
|              o  Ensures CLASSPATH env. variable is set             |
|              o  Ensures CLASSPATH includes javapart.zip            |
|                                                                    |
| Returns:     S_OK upon successful completion.                      |
|              E_FAIL otherwise.                                     |
|                                                                    |
+-------------------------------------------------------------------*/
long CheckEnvironment ()
{
	char buffer [255];
	int size = sizeof (buffer);
	int result = S_OK;

	/*
	 *  Ensure that CLASSPATH environment variable is set...
	 */
	if (GetEnvironmentVariable ("CLASSPATH", buffer, size) == 0) {
		HelpDialog dialog (HWND_DESKTOP);
		dialog.Show (HELP_CLASSPATH_NOT_SET);
		result = E_FAIL;
	} else {
		/*
		 *  Ensure that CLASSPATH environment variable includes
		 *  javapart.zip (the JavaPart classes)...
		 */
		strupr (buffer);
		if (strstr (buffer, "JAVAPART.ZIP") == NULL) {
			HelpDialog dialog (HWND_DESKTOP);
			dialog.Show (HELP_CLASSPATH_MISSING_JAVAPART);
			result = E_FAIL;
		}
	}
	return result;
}


/*-------------------------------------------------------------------+
|                         GetSamplesPath ()                          |
| ================================================================== |
|                                                                    |
| Function:    Returns $ODSRC\include (if $ODSRC is set)...          |
|                                                                    |
| Returns:     The samples path or NULL if $ODSRC is not set...      |
|                                                                    |
+-------------------------------------------------------------------*/
char* GetSamplesPath ()
{
	static char buffer [MAX_PATH];
	int size = sizeof (buffer);
	char* path = NULL;

	/*
	 *  Ensure that CLASSPATH environment variable is set...
	 */
	if (GetEnvironmentVariable ("ODSRC", buffer, size)) {
		strcat (buffer, "\\include");
		path = buffer;
	} 

	return path;
}


/*-------------------------------------------------------------------+
|                          SelectApplet ()                           |
| ================================================================== |
|                                                                    |
| Function:    Select an Applet via the file selection dialog box.   |
|                                                                    |
| Returns:     An applet tag or NULL if an error occurred.           |
|                                                                    |
+-------------------------------------------------------------------*/
AppletTag* SelectApplet (const char* title)
{
	AppletTag* tag = NULL;

	char filename [MAX_PATH];
	OPENFILENAME  of;

	memset (&of, '\0', sizeof (of));
	lstrcpy (filename, "*.htm*");

	of.lStructSize      = sizeof (OPENFILENAME);
	of.hwndOwner        = HWND_DESKTOP;
	of.lpstrFilter      = "html documents (*.htm*)\0*.htm*\0All (*.*)\0*.*\0";
	of.lpstrCustomFilter= NULL;
	of.nFilterIndex     = 1;
	of.lpstrFile        = (LPSTR) filename;
	of.nMaxFile         = MAX_PATH;
	of.lpstrInitialDir  = GetSamplesPath ();
	of.lpstrTitle       = title;
	of.Flags            = OFN_HIDEREADONLY|OFN_FILEMUSTEXIST;
	of.lpstrDefExt      = "htm*";

	if (GetOpenFileName (&of)) {

		/*
		 *  Prefix with 'file:///'...
		 */
		char url [255];
		strcpy (url, "file:///");
		strcat (url, of.lpstrFile);

		tag = new AppletTag (url);

	}
	return tag;
}


/*-------------------------------------------------------------------+
|                      ChooseBeanDialogProc ()                       |
| ================================================================== |
|                                                                    |
| Function:    Dialog Procedure for Select Bean Dialog.              |
|                                                                    |
+-------------------------------------------------------------------*/
BOOL CALLBACK ChooseBeanDialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
   switch (uMsg) {
   case WM_INITDIALOG:
      SetFocus(GetDlgItem(hwnd, ID_BEAN_NAME));
      break;
   case WM_COMMAND:
      switch (LOWORD(wParam)) {
      case IDOK:
         {
            char* BeanClassName = new char[256];
            GetDlgItemText(hwnd, ID_BEAN_NAME, BeanClassName, 255);
            EndDialog(hwnd, (int) BeanClassName);
         }
         break;
      case IDCANCEL:
         EndDialog(hwnd, 0);
         break;
      } /* end switch */
   } /* end switch */
   return 0;
}


/*-------------------------------------------------------------------+
|                           SelectBean ()                            |
| ================================================================== |
|                                                                    |
| Function:    Select a Bean via a simple string input dialog box.   |
|                                                                    |
| Returns:     A bean tag or NULL if an error occurred.              |
|                                                                    |
+-------------------------------------------------------------------*/
BeanTag* SelectBean (HWND parentWindow)
{
	BeanTag* tag = NULL;

      char* beanClassName = NULL;
      HMODULE hmod = GetModuleHandle(JavaPartDllName);
      int rc = DialogBox(hmod, MAKEINTRESOURCE(ChooseBeanDialogResource),
         parentWindow, (DLGPROC) &ChooseBeanDialogProc);

      if (rc>0) {
         beanClassName = (char *) rc;
         tag = new BeanTag(beanClassName);
      } /* endif */

	return tag;
}
