//
//  BanerView.m
//  Machicomi
//
//  Created by Phan Quang Hoang on 9/20/13.
//  Copyright (c) 2013 Phan Quang Hoang. All rights reserved.
//

#import "BanerView.h"
#import "AppDelegate.h"

@interface BanerView ()
{
	int webViewLoads_;
	NSTimer *timer;
}
@end

@implementation BanerView

@synthesize indicatorView;
@synthesize activityView;
@synthesize _webView;

/*
 ⁃	Dealloc
 ⁃	Initialization
 ⁃	View lifecycle
 ⁃	Private methods
 ⁃	Button selectors
 ⁃	Delegates
 */

#pragma mark - Dealloc
- (void)didReceiveMemoryWarning
{
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

#pragma mark - Initialization
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		// Custom initialization
		_url = nil;
	}
	return self;
}

/* Update layout */
- (void)resizeSubView
{
	CGRect rect = _webView.frame;
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){
		rect.size.height = SIZE_HEIGHT - 2.0f;
	}
	else{
		rect.size.height = SIZE_HEIGHT - 20 - 52 - 44;
	}
	_webView.frame = rect;
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
	[super viewDidLoad];
	// Do any additional setup after loading the view from its nib.
	
	UIButton *leftButton = [[UIButton alloc] init];
	UIImage *headerBackImage = gImageHeaderBack;
	[leftButton setBackgroundImage:headerBackImage forState:UIControlStateNormal];
	[leftButton addTarget:self action:@selector(backView) forControlEvents:UIControlEventTouchUpInside];
	[leftButton setFrame:CGRectMake(0, 0, 50, 20)];
	
	UIBarButtonItem *leftButtonItem;
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
		[leftButton setFrame:CGRectMake(0, 0, 50, 20)];
		
		leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
		NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
										[UIColor blackColor],
										NSForegroundColorAttributeName,
										[UIFont boldSystemFontOfSize:17.0f], NSFontAttributeName, nil];
		self.navigationController.navigationBar.titleTextAttributes = textAttributes;
		
		UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
										   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
										   target:nil action:nil];
		negativeSpacer.width = -8;// it was -6 in iOS 6
		[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:negativeSpacer, leftButtonItem, nil] animated:NO];
//	}
//	else{
//		leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//		self.navigationItem.leftBarButtonItem = leftButtonItem;
//		NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys:
//										  [UIColor blackColor], UITextAttributeTextColor,
//										  [UIFont boldSystemFontOfSize:17.0f], UITextAttributeFont, nil];
//
//		[self.navigationController.navigationBar setTitleTextAttributes:textTitleOptions];
	}
	
	
	[self addReloadWebView];
	
	// ActivityIndicator
	activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	activityView.color = [UIColor grayColor];
	CGRect frame = activityView.frame;
	frame.origin.x = self.view.frame.size.width / 2 - frame.size.width / 2;
	frame.origin.y = SIZE_HEIGHT / 2 - frame.size.height / 2;
	activityView.frame = frame;
	activityView.hidesWhenStopped = YES;
	[SVProgressHUD dismiss];

	[self.tabBarController.view addSubview:activityView];

	[self loadWebView];
	
	UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeRight:)];
	swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
	[self.view addGestureRecognizer:swipeRight];
}

- (void)viewWillAppear:(BOOL)animated
{
	[self appDelegate].isScreen = WEB_VIEW;

	[super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
	
	[SVProgressHUD dismiss];
	[timer invalidate];
	timer = nil;
	webViewLoads_ = 0;
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
	[self resizeSubView];
}

#pragma mark - Reload webview
- (void)loadWebView
{
	if(isLoadingWeb){
		[_webView stopLoading];
		isLoadingWeb = NO;
		[self loadingWeb:isLoadingWeb];
	}else {
		// MODIFY 2015-07-16
//		NSString *url = BannerAddres;
		NSString *url = nil;
		if (_url.length) {
			url = _url;
		} else {
			url = BannerAddres;
		}
		
		NSURL *urlRequest = [NSURL URLWithString:url];
		NSMutableURLRequest *requestObj = [[NSMutableURLRequest alloc] initWithURL:urlRequest];
		[requestObj setHTTPMethod:@"POST"];
		NSString *body = [NSString stringWithFormat:@"hostid=%@", [self appDelegate].hostId];
		[requestObj setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
		[_webView loadRequest:requestObj];
		
		isLoadingWeb = YES;
		[self loadingWeb:isLoadingWeb];
	}
}

- (void)reloadWebView
{
	webViewLoads_ = 0;
	// Background reload page
	if(isLoadingWeb) {
		[SVProgressHUD dismiss];
		[_webView stopLoading];
		isLoadingWeb = NO;
		[self loadingWeb:isLoadingWeb];
	}else {
		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
		if ([connectManager isConnectNetwork]) {
			[SVProgressHUD show];
			[_webView reload];
			isLoadingWeb = YES;
			[self loadingWeb:isLoadingWeb];
		}
	}
}

- (void)reloadWebView:(id)sender
{
	webViewLoads_ = 0;
	// Button selectors
	if(isLoadingWeb) {
		[SVProgressHUD dismiss];
		[_webView stopLoading];
		isLoadingWeb = NO;
		[self loadingWeb:isLoadingWeb];
	}else {
		// MODIFY 2015-09-09
		if ([[self appDelegate] isOnlineAndAlert:self]) {
			[SVProgressHUD show];
			[_webView reload];
			isLoadingWeb = YES;
			[self loadingWeb:isLoadingWeb];
		}
		
//		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//		if ([connectManager isConnectNetwork]) {
//			[SVProgressHUD show];
//			[_webView reload];
//			isLoadingWeb = YES;
//			[self loadingWeb:isLoadingWeb];
//			
//		} else {
//			// iOS8対応	MODIFY 2015-06-24
//			if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//				// iOS8 and later
//				UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//				// addActionした順に左から右にボタンが配置されます
//				[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:nil]];
//				[self presentViewController:alertController animated:YES completion:nil];
//			} else {
//				// iOS7 and earlier
//				UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE delegate:self cancelButtonTitle:OK_MESSAGE otherButtonTitles: nil];
//				[alertView show];
//			}
//		}
	}
}


- (void)loadingWeb:(BOOL)isLoading
{
	if(isLoading) {
		[rightButton setImage:gImageCloseNormal forState:UIControlStateNormal];
	}else {
		[rightButton setImage:gImageReloadGroup forState:UIControlStateNormal];
	}
}

- (void)addReloadWebView
{
	// Reload barButton
	// Add button item to right navigation
	rightButton = [[UIButton alloc] init];
	[rightButton setImage:gImageReloadGroup forState:UIControlStateNormal];
	[rightButton setFrame:CGRectMake(0, 0, 50, 20)];
	[rightButton addTarget:self action:@selector(reloadWebView:) forControlEvents:UIControlEventTouchUpInside];
	
	UIBarButtonItem *rightButtonItem;
	// MODIFY 2015-06-12 systemVersion => NSFoundationVersionNumber
	if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
//	if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
		rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
		
		UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
										   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
										   target:nil action:nil];
		negativeSpacer.width = -8;// it was -6 in iOS 6
		[self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:negativeSpacer, rightButtonItem, nil] animated:NO];
		
	}
	else{
		rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
		self.navigationItem.rightBarButtonItem = rightButtonItem;
	}

	
}

#pragma mark - Private methods
/* App Delegate */
- (AppDelegate *)appDelegate
{
	return  (AppDelegate *)[UIApplication sharedApplication].delegate;
}

#pragma mark - UISwipeGestureRecognizer
- (void)swipeRight:(UISwipeGestureRecognizer*)gestureRecognizer
{
	if ([_webView canGoBack]) {
		[_webView goBack];
	}
}

#pragma mark - Button selectors
/* Back view */
- (void)backView
{
	// Title logo
	UIImage *image = [UIImage imageNamed:@"logo_machicomi"];
	UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
	self.navigationItem.titleView = imageView;
	
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	if(navigationType == UIWebViewNavigationTypeLinkClicked
	   || navigationType==UIWebViewNavigationTypeFormSubmitted /*ADD 2015-09-14*/) {
		webViewLoads_ = 0;

		// MODIFY 2015-09-09
		if ( ! [[self appDelegate] isOnlineAndAlert:self]) {
			// OFFLINE
			return NO;
		}
		
//		ConnectionManager *connectManager = [[ConnectionManager alloc] init];
//		if ([connectManager isConnectNetwork]) {
//		} else {
//			// iOS8対応	MODIFY 2015-06-24
//			if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
//				// iOS8 and later
//				UIAlertController *alertController = [UIAlertController alertControllerWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE preferredStyle:UIAlertControllerStyleAlert];
//				// addActionした順に左から右にボタンが配置されます
//				[alertController addAction:[UIAlertAction actionWithTitle:OK_MESSAGE style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//				}]];
//				[self presentViewController:alertController animated:YES completion:nil];
//			} else {
//				// iOS7 and earlier
//				[UIAlertView showWithTitle:OFFLINE_TITLE message:OFFLINE_MESSAGE cancelButtonTitle:OK_MESSAGE otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//					
//				}];
//			}
//			return NO;
//		}
		
	}
	
	NSString *urlString = [[request URL] absoluteString];
	NSString *stringBody = [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding];
 	if(stringBody == nil)
		stringBody = @"";
    
    NSLog(@"AAA URL: %@  stringBody:%@", urlString, stringBody);

	if([stringBody rangeOfString:@"dbrowser"].location != NSNotFound) {
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
		return NO;
	}
	
	@try {
		urlString = [[urlString componentsSeparatedByString:@"?"] objectAtIndex:1];
		
		if(urlString == nil)
			urlString = @"";
		
		if([urlString rangeOfString:@"dbrowser"].location != NSNotFound) {
			urlString = [[request URL] absoluteString];
			urlString = [urlString stringByReplacingOccurrencesOfString:@"dbrowser&" withString:@""];
			urlString = [urlString stringByReplacingOccurrencesOfString:@"&dbrowser" withString:@""];
			urlString = [urlString stringByReplacingOccurrencesOfString:@"?dbrowser" withString:@""];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
			return NO;
		}
	}
	@catch (NSException *exception) {
		//
	}
	
	return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
	if(webViewLoads_ == 0) {
		[SVProgressHUD show];
		isLoadingWeb = YES;
		[self loadingWeb:isLoadingWeb];
		[timer invalidate];
		timer = nil;
		timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(webViewActuallyFinished) userInfo:nil repeats:NO];
	}
	webViewLoads_++;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    webViewLoads_--;
//    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(webViewActuallyFinished) userInfo:nil repeats:NO];
	[timer invalidate];
	timer = nil;
	
	[self webViewActuallyFinished];
}

- (void)webViewActuallyFinished
{
//    NSLog(@"Did finished %d", webViewLoads_);
//    if (webViewLoads_ > 0) {
//        return;
//    }
	NSString *theTitle = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
	self.navigationItem.title = theTitle;
	[SVProgressHUD dismiss];
	isLoadingWeb = NO;
	[self loadingWeb:isLoadingWeb];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//    webViewLoads_--;
	[SVProgressHUD dismiss];
	isLoadingWeb = NO;
	[self loadingWeb:isLoadingWeb];
}
@end
