//
// IMWebViewController.m
// Project
//
// Created by haibara on 2/27/16.
//
//

#import "IMWebViewController.h"
#import <WebKit/WebKit.h>
#import "SDK.h"
#import "MailViewController.h"
#import <libextobjc/EXTScope.h>

@interface DZNWebViewController ()
- (void)commonInit;
@end

@interface IMWebViewController () <WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, strong) NSString *htmlString;
@property (nonatomic, strong) NSURL *baseUrl;
@end

@implementation IMWebViewController

@synthesize showLoadingProgress = _showLoadingProgress;

- (void)viewDidLoad {
	[super viewDidLoad];

	if (self.htmlString) {
		self.showLoadingProgress = NO;
	}
	if (self.autoshrink) {
		NSString *js = @"\
		var viewport = document.head.querySelector('meta[name=viewport]'); \
		if (!viewport) { \
            viewport = document.createElement('meta'); \
            viewport.setAttribute('name', 'viewport'); \
            document.head.appendChild(viewport); \
		} \
        var content = viewport.getAttribute('content'); \
        if (content == undefined || content.indexOf('device-width') < 0) { \
            viewport.setAttribute('content', 'width=device-width'); \
        } \
        ";
		WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
		[self.webView.configuration.userContentController addUserScript:script];
	}
	if (!UIEdgeInsetsEqualToEdgeInsets(self.webContainerInset, UIEdgeInsetsZero)) {
		NSString *js = [NSString stringWithFormat:@"\
        var style = document.createElement('style'); \
        style.setAttribute('style', 'text/css'); \
        style.innerHTML = 'body{padding:%gpx %gpx %gpx %gpx;}'; \
        document.head.appendChild(style); \
        ", self.webContainerInset.top, self.webContainerInset.right, self.webContainerInset.bottom, self.webContainerInset.left];
		WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
		[self.webView.configuration.userContentController addUserScript:script];
	}
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];

	if (self.htmlString) {
		[self.webView loadHTMLString:self.htmlString baseURL:self.baseUrl];
	}
}

#pragma mark - Property

- (BOOL)showLoadingProgress {
	return _showLoadingProgress && [self.navigationController.topViewController isKindOfClass:self.class];
}

#pragma mark - Public

- (instancetype)initWithURLString:(NSString *)urlString {
	return [self initWithURL:[NSURL URLWithString:urlString]];
}

- (instancetype)initWithHTMLString:(NSString *)htmlString {
	if (self = [self init]) {
		self.htmlString = htmlString;
	}
	return self;
}

- (instancetype)initWithHTMLString:(NSString *)htmlString baseUrl:(NSURL *)baseUrl {
	if (self = [self init]) {
		self.htmlString = htmlString;
		self.baseUrl = baseUrl;
	}
	return self;
}

#pragma mark - Protected

- (void)commonInit {
	[super commonInit];

	self.edgesForExtendedLayout = UIRectEdgeNone;
	self.showPageTitleAndURL = NO;
	self.allowHistory = NO;
	self.hideBarsWithGestures = NO;
	self.supportedWebNavigationTools = DZNWebNavigationToolNone;
	self.supportedWebActions = DZNWebActionNone;
	if ([self.webView respondsToSelector:@selector(setAllowsLinkPreview:)]) {
		self.webView.allowsLinkPreview = NO;
	}
}

- (void)loadURL:(NSURL *)URL {
	if (!URL) {
		return;
	}
	[super loadURL:URL];
}

#pragma mark - Navigation delegate

- (void)webView:(DZNWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
	if (self.htmlString) {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	} else {
		[super webView:webView didCommitNavigation:navigation];
	}
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
	if (navigationAction.navigationType != WKNavigationTypeOther) {
		NSString *scheme = navigationAction.request.URL.scheme;
		if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
			decisionHandler(WKNavigationActionPolicyCancel);
			return;
		}
		if (self.navigationActionDecisionHandler) {
			decisionHandler(self.navigationActionDecisionHandler(webView, navigationAction));
			return;
		}
	}
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
	decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(DZNWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
	[super webView:webView didFinishNavigation:navigation];
	if (!self.title && webView.title) {
		self.title = webView.title;
	}
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"

- (void)webView:(DZNWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

#pragma mark - UI delegate

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
	if (navigationAction.navigationType == WKNavigationTypeOther) {
		if (self.navigationActionDecisionHandler) {
			if (self.navigationActionDecisionHandler(webView, navigationAction) == WKNavigationActionPolicyAllow) {
				[webView loadRequest:navigationAction.request];
			}
		}
	}
	return nil;
}

#pragma clang diagnostic pop

@end
