//
//  iOSSimpleHTMLView.m
//

#import "SimpleHTMLView.h"
#import "NSURLImageProtocol.h"

static NSString * noNilString(NSString * input) {
	if (input) return input;
	return @"";
}

@implementation SimpleHTMLView

- (void)awakeFromNib {
	[super awakeFromNib];
	[NSURLProtocol registerClass:[NSURLImageProtocol class]];
	self.delegate = self;
}

- (void)setContent:(NSString *)content {
	NSString * htmlString = [NSString stringWithFormat:@"%@%@%@",
							 noNilString(self.contentHeader),
							 noNilString(content),
							 noNilString(self.contentFooter)];
	[self loadHTMLString:htmlString baseURL:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	if (navigationType == UIWebViewNavigationTypeOther) return YES;
	NSURL * url = request.URL;
	[[UIApplication sharedApplication] openURL:url];
	return NO;
}

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
	if (self.autoHeight) {
		[self sizeToFitWidth];
		[LayoutResolver layoutViewController:self.controller];
	}
}

- (void)sizeToFitWidth {
	
	self.scrollView.scrollEnabled = NO;
	CGRect frame = self.frame;
	
	// Set the height to a small one.
	// Set webView's Frame, forcing the Layout of its embedded scrollView with current Frame's constraints (Width set above).
	frame.size.height = 1;        
	self.frame = frame;       
	
	// Get the corresponding height from the webView's embedded scrollView.
	frame.size.height = self.scrollView.contentSize.height;  
	
	// Set the scrollView contentHeight back to the frame itself.
	self.frame = frame;
	
	if ([self.superview isKindOfClass:[UIScrollView class]]) {
		[self.superview needsUpdateConstraints];
	}
}

- (void)setAutoHeight:(BOOL)autoHeight {
	_autoHeight = autoHeight;
	self.scrollView.bounces = !autoHeight;
}

- (void)setController:(NSObject<ViewControllerWithLayoutConstraints> *)controller {
	_controller = controller;
}

@end
