//
//  WebView.m
//  mySTEP
//
//  Created by Dr. H. Nikolaus Schaller on Mon Jan 05 2004.
//  Revised May 2006
//  Copyright (c) 2004 DSITRI. All rights reserved.
//

#import "Private.h"
#import "WebHTMLDocumentRepresentation.h"
#import <WebKit/WebView.h>
#import <WebKit/WebFrame.h>

@implementation WebView

static NSMutableDictionary *_viewClasses;
static NSMutableDictionary *_representationClasses;
static NSArray *_htmlMimeTypes;

+ (BOOL) canShowMIMEType:(NSString *) MIMEType;
{
	return [self _viewClassForMIMEType:MIMEType] != Nil;
}

+ (BOOL) canShowMIMETypeAsHTML:(NSString *) MIMEType
{
	return [_htmlMimeTypes containsObject:MIMEType];	// FIXME: case insensitive???
}

+ (void) initialize;
{
#if 0
	NSLog(@"WebView +initialize");
#endif
	[self setMIMETypesShownAsHTML:[NSArray arrayWithObjects:@"text/html", nil]];
	[self registerViewClass:self
		representationClass:[_WebHTMLDocumentRepresentation class]
				forMIMEType:@"text/html"];	// we are ourselves the default for HTML
}

+ (NSArray *) MIMETypesShownAsHTML; { return _htmlMimeTypes; }

+ (void) registerViewClass:(Class) class representationClass:(Class) repClass forMIMEType:(NSString *) type;
{
#if 0
	NSLog(@"registerViewClass:%@ representationClass:%@ forMIMEType:%@", NSStringFromClass(class), NSStringFromClass(repClass), type);
#endif
	if(!_viewClasses)
		{ // allocate container(s)
		_viewClasses=[[NSMutableDictionary alloc] initWithCapacity:5];
		_representationClasses=[[NSMutableDictionary alloc] initWithCapacity:5];
		}
	if(class != Nil && repClass != Nil)
		{
		[_viewClasses setObject:class forKey:type];
		[_representationClasses setObject:repClass forKey:type];
		}
	else
		{
		[_viewClasses removeObjectForKey:type];
		[_representationClasses removeObjectForKey:type];
		}
}

+ (void) setMIMETypesShownAsHTML:(NSArray *) types;
{
	ASSIGN(_htmlMimeTypes, types);
}

+ (Class) _representationClassForMIMEType:(NSString *) type;
{ // find representation class
	Class cls;
  // strip off ;parameters from type
	if([self canShowMIMETypeAsHTML:type])
		type=@"text/html";
	if((cls=[_representationClasses objectForKey:type]))
		return cls;	// appears to match
	// get major type component only and append /
	cls=[_representationClasses objectForKey:type];
	return cls;
}

+ (Class) _viewClassForMIMEType:(NSString *) type;
{ // find view class
	Class cls;
	// strip off ;parameters from type
	if([self canShowMIMETypeAsHTML:type])
		type=@"text/html";
	if((cls=[_viewClasses objectForKey:type]))
		return cls;	// appears to match
					// get major type component only and append /
	cls=[_viewClasses objectForKey:type];
	return cls;
}

- (id) initWithFrame:(NSRect) rect;
{
	return [self initWithFrame:rect frameName:nil groupName:nil];
}

- (id) initWithFrame:(NSRect) rect frameName:(NSString *) name groupName:(NSString *) group;
{
#if 0
	NSLog(@"mySTEP: WebView initWithFrame:%@", NSStringFromRect(rect));
#endif
	if((self=[super initWithFrame:rect]))
		{
		WebFrameView *fview=[[WebFrameView alloc] initWithFrame:rect];	// add a main frame
		_mainFrame=[[WebFrame alloc] initWithName:name webFrameView:fview webView:self];
		[fview _setDocumentView:nil];	// will be set as soon as MIME-type becomes known from data source
		[fview _setWebFrame:_mainFrame];
		[fview setAllowsScrolling:YES];	// man view can scroll
		[fview release];
		_groupName=[group retain];
		}
	return self;
}

#if 0
- (void) awakeFromNib
{
	NSLog(@"mySTEP: WebView awakeFromNib");
}
#endif

- (void) dealloc;
{
	[_mainFrame release];
	[_groupName release];
	[_backForwardList release];
	[_customAgent release];
	[_customTextEncoding release];
	[_applicationName release];
	[_dataSource release];
	[super dealloc];
}

- (WebFrame *) mainFrame;   { return _mainFrame; }
- (id) UIDelegate; { return _uiDelegate; }
- (void) setUIDelegate:(id) uid; { _uiDelegate=uid; }
- (NSString *) groupName; { return _groupName; }
- (void) setGroupName:(NSString *) str; { ASSIGN(_groupName, str); }

- (WebBackForwardList *) backForwardList; { return _backForwardList; }

- (void) setMaintainsBackForwardList:(BOOL) flag;
{
	if(flag && !_backForwardList)
		_backForwardList=[[WebBackForwardList alloc] init];
	else if(!flag && _backForwardList)
		[_backForwardList release], _backForwardList=nil;
}

- (NSString *) applicationNameForUserAgent; { return _applicationName; }
- (void) setApplicationNameForUserAgent:(NSString *) name; { _applicationName=[name retain]; }
- (NSString *) customUserAgent; { return _customAgent; }
- (void) setCustomUserAgent:(NSString *) agent; { _customAgent=[agent retain]; }
- (NSString *) customTextEncodingName; { return _customTextEncoding; }
- (void) setCustomTextEncodingName:(NSString *) name; { _customTextEncoding=[name retain]; }

	// FIXME

- (BOOL) canGoBack; { return NO; }
- (BOOL) canGoForward; { return NO; }

- (IBAction) takeStringURLFrom:(id) sender;
{
	// add http:// prefix if there is none yet
	NSURL *u=[NSURL URLWithString:[sender stringValue]];
#if 1
	NSLog(@"takeStringURL %@", u);
#endif
	[_mainFrame loadRequest:[NSURLRequest requestWithURL:u]];
}

- (double) estimatedProgress;
{
// FIXME
	return 0.0;
}

- (IBAction) reload:(id) sender;
{
	[_mainFrame reload];
}

- (IBAction) stopLoading:(id) sender;
{
	[_mainFrame stopLoading];
}

- (NSString *) stringByEvaluatingJavaScriptFromString:(NSString *) script;
{
	return @"JavaScript not implemented";
}

- (IBAction) goBack:(id) sender; { NIMP; }
- (IBAction) goForward:(id) sender; { NIMP; }
- (IBAction) makeTextLarger:(id) sender; { NIMP; }
- (IBAction) makeTextSmaller:(id) sender; { NIMP; }

// <WebDocumentView> protocol

- (void) dataSourceUpdated:(WebDataSource *) source;
{
	// reload/redraw or whatever we need from _representation
	// pull out background?
	NIMP;
}

- (void) layout;
{
}

- (void) setDataSource:(WebDataSource *) source; { _dataSource=[source retain]; }

- (void) setNeedsLayout:(BOOL) flag;
{
	NIMP;
}

- (void) viewDidMoveToHostWindow;
{
	NIMP;
}

- (void) viewWillMoveToHostWindow:(NSWindow *) win;
{
	NIMP;
}

- (void) drawRect:(NSRect) rect;
{
	[[NSColor redColor] set];
	NSRectFill(rect);
	// draw page background
	[@"WebView" drawAtPoint:NSMakePoint(10,10) withAttributes:nil];
}

- (BOOL) validateMenuItem:(id <NSMenuItem>) menuItem
{
	NSString *sel=NSStringFromSelector([menuItem action]);
	if([sel isEqualToString:@"goBack:"]) return [self canGoBack];
	if([sel isEqualToString:@"goForward:"]) return [self canGoForward];
	return YES;
}

// private methods!

- (BOOL) drawsBackground;
{
	return NO;
}

- (void) setDrawsBackground:(BOOL) flag;
{
}

/* callbacks we should generate for UIdelegate!

- (WebView *) webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request

	[_uiDelegate webViewShow:self];

[_uiDelegate webView:self didCommitLoadForFrame:(WebFrame *)frame];	// set status "Loading..."
[_uiDelegate webView:self didStartProvisionalLoadForFrame:(WebFrame *)frame];	// set status "Loading URL"
[_uiDelegate webView:self didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame];	// update title
[_uiDelegate webView:self didFinishLoadForFrame:(WebFrame *)frame];	// set status "Done."

*/

@end