//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	This program is distributed in the hope that it will be 
//	useful, but WITHOUT ANY WARRANTY; without even the 
//	implied warranty of MERCHANTABILITY or FITNESS FOR A 
//	PARTICULAR PURPOSE.
//
//

extern "C" {

#include	<InternetConfig.h>
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<AppConstants.h>
#include "machine/include.h"

bool ConfirmBrowserSetup();
void SendQuit(OSType appSign);
void CheckICMapEntry(void);


bool
ConfirmBrowserSetup()
{
	static short ans = -1;
	if ( ans == -1 )
		ans = Alert(ALRT_BrowserSetup, 0);
	if ( ans == BrowserSetup_OK )
		return true;
	return false;
}

void
SendQuit(OSType appSign)
{
	AEDesc myAddress;
	AppleEvent theEvent, theReply;
	OSErr er;
	ProcessSerialNumber procNum = {0, kNoProcess};
	ProcessInfoRec info;
	info.processInfoLength = sizeof(ProcessInfoRec);
	FSSpec procFile;
	Str255 appName;
	info.processName = appName;
	info.processAppSpec = &procFile;
	
	while ( (er = GetNextProcess(&procNum)) == noErr ) {
		er = GetProcessInformation(&procNum, &info);
		if ( info.processSignature == appSign ) {
			appName[appName[0]+1] = 0;
			printf("Quit %s...", appName+1);
			fflush(stdout);
			er = SetFrontProcess(&procNum);
			er = AECreateDesc(typeProcessSerialNumber, &procNum, sizeof(procNum), &myAddress);
			er = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &myAddress, 
				kAutoGenerateReturnID, kAnyTransactionID, &theEvent);
			er = AESend(&theEvent, &theReply, kAENoReply+kAECanInteract, 
				kAEHighPriority, kAEDefaultTimeout, 0, 0);
			er = AEDisposeDesc(&theEvent);
			er = AEDisposeDesc(&theReply);
			while ( (er = GetProcessInformation(&procNum, &info)) == noErr ) {
				EventRecord event;
				WaitNextEvent(nullEvent, &event, 15, 0);
			}
			printf("OK\n");
		}
	}
}



void
CheckICMapEntry(void)
{
	OSType browserSign = 0;
	ICInstance inst;
	ICMapEntry entry;
	ICAttr attr = 0;
	char flag;
	Handle mappings = NewHandle(0);
	long a, count, i, pos;
	char buf[256];
	ICAppSpec appSpec;
	void netscape_change_settings();

	printf("=== Checking Internet Config ===\n");

	a = ICStart(&inst, AppType);
	a |= ICBegin(inst, icReadWritePerm);
	a |= ICFindPrefHandle(inst, kICMapping, &attr, mappings);
	
	if ( a ) {
		printf("Internet Config Error (%d)\n", a);
		goto end;
	}
	
	pos = sizeof(appSpec);
	if ( ICGetPref(inst, "\pHelper¥http", &attr, &appSpec, &pos) == noErr ) {
		p2cstrcpy(buf, appSpec.name);
		browserSign = appSpec.fCreator;
		printf("Web Browser : %s [%c%c%c%c]\n", buf, 
			(char)(browserSign>>24), (char)((browserSign>>16)&0xff),
			(char)((browserSign>>8)&0xff), (char)(browserSign)&0xff);
		if ( ! UEnvironment::IsRunningOSX() && browserSign == NetscapeSign ) {
			printf("=== Checking Netscape Regitry ===\n");
			netscape_change_settings();
		}
	}

retry:
	// Delete invalid ".gb" map entry
	pos = 0;
	flag = 0;
	a = ICCountMapEntries(inst, mappings, &count);
	printf("IC map entries count = %d\n",count);
	for ( i = 0;  i < count;  i++ ) {
		a = ICGetMapEntry(inst, mappings, pos, &entry);
		p2cstrcpy(buf, entry.extension);
		if ( strstr(buf, ".gb") ) {
			printf("Entry ");
			p2cstrcpy(buf, entry.entryName);
			printf("%s", buf);
			p2cstrcpy(buf, entry.extension);
			printf("(%s, ", buf);
			printf("0x%04x)", entry.flags);
			printf(" Found.\n");
			if ( entry.fileCreator == AppType && entry.postCreator == AppType ) {
				flag = 1;
				break;	// valid mapping is found
			}
			if ( ! ConfirmBrowserSetup() ) {
				return;
			}
			SendQuit(browserSign);
			a = ICDeleteMapEntry(inst, mappings, pos);
			goto retry;
		}
		pos += entry.totalLength;
	}

	// Add ".gb" map entry
	if ( flag == 0 ) {
		entry.totalLength = 70;
		entry.fixedLength = kICMapFixedLength;
		entry.version = 0;
		entry.fileType = 'TEXT';
		entry.fileCreator = AppType;
		entry.postCreator = AppType;
		entry.flags = 0x0c;
		c2pstrcpy(entry.extension, ".gb");
		c2pstrcpy(entry.creatorAppName, "COSMOS");
		c2pstrcpy(entry.postAppName, "COSMOS");
		c2pstrcpy(entry.MIMEType, "text/gb");
		c2pstrcpy(entry.entryName, "Globalbase");

		if (ConfirmBrowserSetup()) {
			SendQuit(browserSign);
			a = ICAddMapEntry(inst, mappings, &entry);
			printf("Entry Add [%d]\n", a);
		}
	}
	
	a = ICSetPrefHandle(inst, kICMapping, attr, mappings);
end:
	ICEnd(inst);
	ICStop(inst);
	
	printf("================================\n");
}

} // extern "C"