//
//  BlockableWebView.m
//  BlockableWebView
//
//  Created by Rafael Seemann on 17/10/16.
//  Copyright © 2016 Rafael Seemann. All rights reserved.
//

#import "BlockableWebView.h"

#import <UIKit/UIKit.h>

#import "RCTAutoInsetsProtocol.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTLog.h"
#import "RCTUtils.h"
#import "RCTView.h"
#import "UIView+React.h"

//NSString *const RCTJSNavigationScheme = @"react-js-navigation";

@interface BlockableWebView () <UIWebViewDelegate, RCTAutoInsetsProtocol>

@property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
@property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
@property (nonatomic, copy) RCTDirectEventBlock onNavigationBlocked;
@property (nonatomic, copy) NSArray *navigationBlockingPolicies;

@end

@implementation BlockableWebView
{
  UIWebView *_webView;
  NSString *_injectedJavaScript;
}

- (void)dealloc
{
  _webView.delegate = nil;
}

- (instancetype)initWithFrame:(CGRect)frame
{
  if ((self = [super initWithFrame:frame])) {
    super.backgroundColor = [UIColor clearColor];
    _automaticallyAdjustContentInsets = YES;
    _contentInset = UIEdgeInsetsZero;
    _webView = [[UIWebView alloc] initWithFrame:self.bounds];
    _webView.delegate = self;
    [self addSubview:_webView];
  }
  return self;
}

RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder)

- (void)goForward
{
  [_webView goForward];
}

- (void)goBack
{
  [_webView goBack];
}

- (void)reload
{
  NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  if (request.URL && !_webView.request.URL.absoluteString.length) {
    [_webView loadRequest:request];
  }
  else {
    [_webView reload];
  }
}

- (void)stopLoading
{
  [_webView stopLoading];
}

- (void)setSource:(NSDictionary *)source
{
  if (![_source isEqualToDictionary:source]) {
    _source = [source copy];
    
    // Check for a static html source first
    NSString *html = [RCTConvert NSString:source[@"html"]];
    if (html) {
      NSURL *baseURL = [RCTConvert NSURL:source[@"baseUrl"]];
      if (!baseURL) {
        baseURL = [NSURL URLWithString:@"about:blank"];
      }
      [_webView loadHTMLString:html baseURL:baseURL];
      return;
    }
    
    NSURLRequest *request = [RCTConvert NSURLRequest:source];
    // Because of the way React works, as pages redirect, we actually end up
    // passing the redirect urls back here, so we ignore them if trying to load
    // the same url. We'll expose a call to 'reload' to allow a user to load
    // the existing page.
    if ([request.URL isEqual:_webView.request.URL]) {
      return;
    }
    if (!request.URL) {
      // Clear the webview
      [_webView loadHTMLString:@"" baseURL:nil];
      return;
    }
    [_webView loadRequest:request];
  }
}

- (void)layoutSubviews
{
  [super layoutSubviews];
  _webView.frame = self.bounds;
}

- (void)setContentInset:(UIEdgeInsets)contentInset
{
  _contentInset = contentInset;
  [RCTView autoAdjustInsetsForView:self
                    withScrollView:_webView.scrollView
                      updateOffset:NO];
}

- (void)setScalesPageToFit:(BOOL)scalesPageToFit
{
  if (_webView.scalesPageToFit != scalesPageToFit) {
    _webView.scalesPageToFit = scalesPageToFit;
    [_webView reload];
  }
}

- (BOOL)scalesPageToFit
{
  return _webView.scalesPageToFit;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
  CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  self.opaque = _webView.opaque = (alpha == 1.0);
  _webView.backgroundColor = backgroundColor;
}

- (UIColor *)backgroundColor
{
  return _webView.backgroundColor;
}

- (NSMutableDictionary<NSString *, id> *)baseEvent
{
  NSMutableDictionary<NSString *, id> *event = [[NSMutableDictionary alloc] initWithDictionary:@{
                                                                                                 @"url": _webView.request.URL.absoluteString ?: @"",
                                                                                                 @"loading" : @(_webView.loading),
                                                                                                 @"title": [_webView stringByEvaluatingJavaScriptFromString:@"document.title"],
                                                                                                 @"canGoBack": @(_webView.canGoBack),
                                                                                                 @"canGoForward" : @(_webView.canGoForward),
                                                                                                 }];
  
  return event;
}

- (void)refreshContentInset
{
  [RCTView autoAdjustInsetsForView:self
                    withScrollView:_webView.scrollView
                      updateOffset:YES];
}

#pragma mark - UIWebViewDelegate methods

- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
{
  static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    navigationTypes = @{
                        @(UIWebViewNavigationTypeLinkClicked): @"click",
                        @(UIWebViewNavigationTypeFormSubmitted): @"formsubmit",
                        @(UIWebViewNavigationTypeBackForward): @"backforward",
                        @(UIWebViewNavigationTypeReload): @"reload",
                        @(UIWebViewNavigationTypeFormResubmitted): @"formresubmit",
                        @(UIWebViewNavigationTypeOther): @"other",
                        };
  });
  
  NSString *sourceURL = (NSString *)self.source[@"uri"];
  NSString *requestURL = (request.URL).absoluteString;
  NSString *namedNavigationType = navigationTypes[@(navigationType)];
  
  NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  [event addEntriesFromDictionary: @{
                                     @"url": requestURL,
                                     @"navigationType": namedNavigationType
                                     }];
  
  BOOL isJSNavigation = [request.URL.scheme isEqualToString:RCTJSNavigationScheme];
  BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  BOOL isLoadingSourceURL = ([sourceURL isEqualToString:requestURL] && !_webView.isLoading);
  BOOL isHTTPRequest = [[request.URL scheme] isEqualToString:@"http"] || [[request.URL scheme] isEqualToString:@"https"];
  
  // skip this for the JS Navigation handler, initial load, iFrames and non-http(s) requests
  if(!isJSNavigation && isTopFrame && !isLoadingSourceURL && isHTTPRequest) {
    BOOL _shouldBlock = false;
    
    if(_navigationBlockingPolicies.count > 0) {
      NSDictionary *currentValues = @{
                                      @"currentURL": sourceURL,
                                      @"url": requestURL,
                                      @"navigationType": namedNavigationType
                                      };
      NSString *eventValue;
      BOOL policyFulfilled;
      
      for(NSDictionary *policy in _navigationBlockingPolicies) {
        // policy with no rules
        if(policy.count < 1) {
          continue;
        }
        
        policyFulfilled = YES;
        
        for(NSString *key in policy) {
          // policy has failed already
          if(!policyFulfilled) break;
          
          eventValue = [currentValues objectForKey:key];
          
          // unverifiable policy rule
          if(!eventValue) {
            RCTLogWarn(@"Could not verify webview loading policy named %@. Failing policy with rules %@", key, policy);
            policyFulfilled = NO;
            break;
          }
          
          NSPredicate *rule = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", [policy objectForKey:key]];
          
          policyFulfilled = [rule evaluateWithObject: eventValue];
        }
        
        if(policyFulfilled) {
          _shouldBlock = !_shouldBlock;
          break;
        }
      }
    }
    
    // call blocked callback
    if(_shouldBlock) {
      if(_onNavigationBlocked) {
        _onNavigationBlocked(event);
      }
      
      return NO;
    }
  }
  
  // skip this for the JS Navigation handler
  if (!isJSNavigation && _onShouldStartLoadWithRequest) {
    if (![self.delegate webView:self
      shouldStartLoadForRequest:event
                   withCallback:_onShouldStartLoadWithRequest]) {
      return NO;
    }
  }
  
  if (_onLoadingStart) {
    // We have this check to filter out iframe requests and whatnot
    if (isTopFrame) {
      _onLoadingStart(event);
    }
  }
  
  // JS Navigation handler
  return !isJSNavigation;
}

- (void)webView:(__unused UIWebView *)webView didFailLoadWithError:(NSError *)error
{
  if (_onLoadingError) {
    if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
      // NSURLErrorCancelled is reported when a page has a redirect OR if you load
      // a new URL in the WebView before the previous one came back. We can just
      // ignore these since they aren't real errors.
      // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
      return;
    }
    
    NSMutableDictionary<NSString *, id> *event = [self baseEvent];
    [event addEntriesFromDictionary:@{
                                      @"domain": error.domain,
                                      @"code": @(error.code),
                                      @"description": error.localizedDescription,
                                      }];
    _onLoadingError(event);
  }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
  if (_injectedJavaScript != nil) {
    NSString *jsEvaluationValue = [webView stringByEvaluatingJavaScriptFromString:_injectedJavaScript];
    
    NSMutableDictionary<NSString *, id> *event = [self baseEvent];
    event[@"jsEvaluationValue"] = jsEvaluationValue;
    
    _onLoadingFinish(event);
  }
  // we only need the final 'finishLoad' call so only fire the event when we're actually done loading.
  else if (_onLoadingFinish && !webView.loading && ![webView.request.URL.absoluteString isEqualToString:@"about:blank"]) {
    _onLoadingFinish([self baseEvent]);
  }
}

@end
