//
//  ExploreViewController.m
//  Project
//
//  Created by Vae on 2018/10/8.
//

#import "ExploreViewController.h"
#import "Vars.h"
#import "WebService.h"
#import "Utility.h"
#import "UIConstants.h"
#import "SDK.h"
#import "Utility.h"
#import "CocoaUtils.h"
#import "IMBarButtonItem.h"
#import "AppTracker.h"
#import "BaseInterception.h"
#import "DrawUtils.h"
#import "WebViewErrorView.h"
#import "CacheData.h"
#import <libextobjc/EXTScope.h>
#import <BlocksKit/BlocksKit+UIKit.h>
#import <MarqueeLabel/MarqueeLabel.h>
#import <PureLayout/PureLayout.h>
#import "InterceptionManager.h"
#import "Vars.h"
@import Foundation;
@interface ExploreViewController ()<WKNavigationDelegate,UIScrollViewDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UIButton *backBarButton;
@property (nonatomic, strong) NSString *baseUrl;
@property (nonatomic, assign) CGFloat contentOffsetY;
@property (nonatomic, strong) MarqueeLabel *titleLabel;
@property (nonatomic, strong) WebViewErrorView *errorView;
@property (nonatomic, assign) BOOL isHtmlLoad;
@property (nonatomic, strong) CacheData *cacheData;
@end

@implementation ExploreViewController

- (instancetype)init {
	if (self = [super init]) {
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
		self.webView = [[WKWebView alloc] init];
		if ([Vars is_bus_site]) {
			[self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:NULL];
		}
	}
	return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	[[AppTracker sharedInstance] sendView:[self class]];
	
	[self loadNavigationBarButton];
	[self loadProgressView];
	[self loadWebView];
	[self injectWebView];
	[self loadHomePage];
	[self loadTitleLabel];

}

-(void)viewDidLayoutSubviews{
	self.webView.frame = self.view.bounds;
}

-(void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	if (@available(iOS 11, *)) {
		[self.navigationItem.titleView autoCenterInSuperview];
	}
}


-(void)loadNavigationBarButton{
	@weakify(self);
	self.backBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
	UIColor *buttonColor ;
	if ([Vars is_bus_site]) {
		buttonColor = [UIColor whiteColor];
	}else{
		buttonColor = [Vars defaultTintColor];
	}
	[self.backBarButton setBackgroundImage:[DrawUtils imageWithFAKIcon:[FAKFontAwesome angleLeftIconWithSize:32] fillColor:buttonColor] forState:UIControlStateNormal];
	[self.backBarButton sizeToFit];
	[self.backBarButton bk_addEventHandler:^(id  _Nonnull sender) {
		@strongify(self);
		[self touchBackEvent];
	} forControlEvents:UIControlEventTouchUpInside];
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBarButton];
	self.backBarButton.hidden = YES;
}

-(void)loadProgressView{
	if ([Vars is_bus_site]) {
		self.progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
		self.progressView.frame = CGRectMake(0, CGRectGetHeight(self.navigationController.navigationBar.frame), CGRectGetWidth(self.view.frame), 0.5);
		self.progressView.trackTintColor = [UIColor whiteColor];
		self.progressView.progressTintColor = [Vars defaultTintColor];
		self.progressView.progress = 0;
		self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.1f);
		[self.navigationController.navigationBar addSubview:self.progressView];
	}
}

-(void)loadTitleLabel{
	self.titleLabel = [[MarqueeLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44) rate:13.0 andFadeLength:5.0];
	self.titleLabel.textAlignment = NSTextAlignmentCenter;
	if ([Vars is_bus_site]) {
		self.titleLabel.textColor = [UIColor whiteColor];
	}else{
		self.titleLabel.textColor = [Vars defaultTintColor];
	}
	self.navigationItem.titleView = self.titleLabel;
}

#pragma mark - property

-(CacheData *)cacheData{
	if (!_cacheData) {
		_cacheData = [[CacheData alloc] init];
	}
	return _cacheData;
}


#pragma mark - Network
- (void)performRequestWithPageContent:(NSString *)pageUrl{
	GetPageContent *getPageContent = [[GetPageContent alloc] init];
	
	NSURL *tempUrl = [NSURL URLWithString:pageUrl];
	NSString *path = [NSString stringWithFormat:@"%@/",tempUrl.path];
	GetPageContentResponse *response = [self.cacheData getpageContentWithKey:path];
	if (response) {
		[self handleRespose:response withPathUrl:pageUrl];
		return;
	}
	if ([pageUrl hasSuffix:@"review-app.html"]){
		NSString *tempPageUrl = tempUrl.path;
		getPageContent.pageUrl = [NSString stringWithFormat:@"%@",[tempPageUrl stringByReplacingOccurrencesOfString:@"-review-app" withString:@""]];
	} else {
		getPageContent.pageUrl = path;
	}
	getPageContent.noCache = YES;
	
	NSDictionary *requestDic = [Utility perlParamXml:[getPageContent innerXML] action:getPageContent.name];
	
	[Utility getXMLFromRequestWithMethod:@"GET" url:getPageContent.address parameters:requestDic success:^(NSString *xml) {
		NSLog(@"%@",xml);
		NSString *responseStr = xml;
		if (![xml containsString:@"html_string"]) {
		responseStr = [responseStr stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
		responseStr = [xml stringByRemovingPercentEncoding];
		}
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[GetPageContentResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			GetPageContentResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else {
				if (response.page_existed) {
					NSURL *tempUrl = [NSURL URLWithString:pageUrl];
					[self.webView loadRequest:[NSURLRequest requestWithURL:tempUrl]];
				}else {
					[self.cacheData setpageContent:response key:getPageContent.pageUrl];
					[self handleRespose:response withPathUrl:pageUrl];
				}
			}
		}
	} error:^(NSError *error) {
		self.errorView.hidden = NO;
		self.progressView.hidden = YES;
	}];
}


-(void)handleRespose:(GetPageContentResponse *)response withPathUrl:(NSString *)pathUrl{
	if ([pathUrl hasSuffix:@"review-app.html"] && response.product_id) {
		[[InterceptionManager sharedManager] handleUrlString:response.product_id];
	}
	else{
		NSString *pageUrl = response.page_url;
		if ([pageUrl containsString:@"&amp"]) {
			pageUrl = [pageUrl stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
		}
		if (!pageUrl) {
			return;
		}
		[[InterceptionManager sharedManager] handleUrlString:pageUrl];
	}
}

#pragma mark - Private

-(void)loadWebView{
	self.webView.allowsLinkPreview = NO;
	self.webView.navigationDelegate = self;
	self.webView.scrollView.delegate = self;
	self.webView.customUserAgent = @"explore";
	[self.view addSubview:self.webView];
}

-(void)loadHomePage{
	[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/homepage/index-app.html",[Vars isLiveServer] ?[Vars liveServer] : [Vars developServer]]]]];
}

-(void)injectWebView{
	NSString *js = @" $('meta[name=description]').remove(); $('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );";
	WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
	[self.webView.configuration.userContentController addUserScript:script];
	if ([Vars is_tours_site]) {
		NSString *cookie = @"document.cookie = 'IvyCustomer_currency = cny_currency'; domain = '.taketours.com'";
		WKUserScript *script = [[WKUserScript alloc] initWithSource:cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
		[self.webView.configuration.userContentController addUserScript:script];
	}
}



#pragma mark - WKNavigationDelegate
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
	NSLog(@"%@",navigationAction.request.URL.absoluteString);
	NSURL *url = navigationAction.request.URL;
	if ([url.absoluteString isEqualToString:@"about:blank"]) {
		decisionHandler(WKNavigationActionPolicyCancel);
		return;
	}
	if ([url.absoluteString containsString:@"-app"]) {
		decisionHandler(WKNavigationActionPolicyAllow);
		return;
	}

	BOOL isHandle = [[InterceptionManager sharedManager] handleUrlString:url.absoluteString];
	if(!isHandle){
		NSMutableString *urlString = [NSMutableString string];
		[urlString appendString:url.absoluteString];
		if ([url hasDirectoryPath]) {
			[urlString appendString:@"index-app.html"];
		}else if([url.pathExtension isEqualToString:@"html"]){
			urlString = [urlString stringByReplacingOccurrencesOfString:@".html" withString:@"-app.html"];
		}else{
			decisionHandler(WKNavigationActionPolicyCancel);
			return;
		}
		[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
		decisionHandler(WKNavigationActionPolicyCancel);
		return;
	}else{
		decisionHandler(WKNavigationActionPolicyCancel);
	}
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
	if (((NSHTTPURLResponse *)navigationResponse.response).statusCode == 200) {
		decisionHandler (WKNavigationResponsePolicyAllow);
	}else {
		decisionHandler(WKNavigationResponsePolicyCancel);
		NSString *urlString = navigationResponse.response.URL.absoluteString;
		NSString *pageString = [urlString stringByReplacingOccurrencesOfString:@"index-app.html" withString:@""];
		[self performRequestWithPageContent:pageString];
	}
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
	self.progressView.hidden = NO;
	self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.1f);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
	self.titleLabel.text = webView.title;
	self.progressView.hidden = YES;
	if ([webView canGoBack]) {
		self.backBarButton.hidden = NO;
	}else{
		self.backBarButton.hidden = YES;
	}
	if(self.setBackHomepageBlock){
		self.setBackHomepageBlock(self.backBarButton.hidden);
	}
}

-(void)refreshWebView{
	self.errorView.hidden = YES;
	if ([self.webView canGoBack]) {
		[self.webView goBack];
	}else{
		[self loadHomePage];
	}
}

-(WebViewErrorView *)errorView{
	if (!_errorView) {
		_errorView = [WebViewErrorView viewFromNib];
		_errorView.frame = self.view.bounds;
		[self.view addSubview:_errorView];
		_errorView.hidden = YES;
		[_errorView.refreshButton addTarget:self action:@selector(refreshWebView) forControlEvents:UIControlEventTouchUpInside];
	}
	return _errorView;
}

- (void)touchBackEvent {
	self.errorView.hidden = YES;
	[self.webView goBack];
}

#pragma mark - scrollerViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	return nil;
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
	if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
		self.progressView.progress = self.webView.estimatedProgress;
		if (self.progressView.progress == 1) {
			[UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
				self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
			} completion:^(BOOL finished) {
				self.progressView.hidden = YES;
			}];
		}
	}else{
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}

-(void)dealloc{
	if ([Vars is_bus_site]) {
		if (self.webView) {
			[self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) context:NULL];
		}
	}
}
@end
