YHExplorerViewController.m 25.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
//
//  YHExplorerViewController.m
//  YohoExplorerDemo
//
//  Created by gaoqiang xu on 2/27/15.
//  Copyright (c) 2015 gaoqiang xu. All rights reserved.
//

static float kprogressViewHeight = 2.0f;
static float kprogressViewRadius = 2.0f;

#define YHE_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#import "YHExplorerViewController.h"
#import "YHWebViewProgress.h"
#import "YHWebViewProgressView.h"
#import "CDVWKWebViewEngine.h"
#import <objc/message.h>
#import "YHInjectConfigManager.h"

@interface YHExplorerViewController ()<WKNavigationDelegate, WKUIDelegate>

@property (strong, nonatomic) NSURLRequest *originRequest;

@property (strong, nonatomic) YHWebViewProgress *progressBar;
@property (strong, nonatomic) YHWebViewProgressView *progressView;

@property (nonatomic) BOOL isAppeared;
@property (strong, nonatomic) NSMutableArray *linkParsers;

@property (strong, nonatomic) NSValue *pointerValue;

@property (strong, nonatomic) UIButton *retryButton;    //重试按钮

@property (strong, nonatomic) NSURL *failURL;  //只有当走失败回调时会有失败url

@end

@implementation YHExplorerViewController


- (void)dealloc
{
    [self stopLoading];
    
    self.progressBar = nil;
    [self removeProgress];
    self.progressView = nil;
    
    if ([self.webViewEngine isKindOfClass:NSClassFromString(@"CDVWKWebViewEngine").class]) {
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
}

- (void)initializeExplorer
{
    _commandDelegate = [[YHExplorerCommandDelegate alloc] initWithViewController:self];
    _commandQueue = [[YHExplorerCommandQueue alloc] initWithViewController:self];
    _progressBarEnabled = NO;
    _automaticallySchemeHandle = YES;
}

- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self initializeExplorer];
    }
    return self;
}

- (instancetype)initWithCurrentNaviBar:(UIView *)currentNaviBar
{
    self = [self init];
    if (self) {
        self.currentNaviBar = currentNaviBar;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isAppeared = NO;
    
    YHLinkDefaultParser *parser = [[YHLinkDefaultParser alloc] init];
    [self registerLinkParser:parser];
    
    if (self.progressBar && !self.progressBar.progressView.superview) {
        [self.currentNaviBar addSubview:self.progressBar.progressView];
    }
    
    if ([self.webViewEngine isKindOfClass:NSClassFromString(@"CDVWKWebViewEngine")]) {
        [self.progressView useWkWebView:self.webView];
        [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    }

    UIScrollView *webScrollView = [self scrollView];
    if ([webScrollView isKindOfClass:UIScrollView.class]) {
        if (@available(iOS 11.0, *)) {
            webScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
                [self setAutomaticallyAdjustsScrollViewInsets:NO];
            }
        }
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.isAppeared = YES;
    if (self.progressBar) {
        if (!self.progressBar.progressView.superview) {
            [self.currentNaviBar addSubview:self.progressBar.progressView];
        } else {
            [self.currentNaviBar bringSubviewToFront:self.progressBar.progressView];
        }
    }
}

/**
 *  移除滚动条
 */
- (void)removeProgress
{
    if (self.progressView) {
        [self.progressView removeFromSuperview];
    }
}

#pragma mark - Override Setter & Getter
- (NSMutableArray *)linkParsers
{
    if (!_linkParsers) {
        _linkParsers = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _linkParsers;
}

- (void)setProgressBarEnabled:(BOOL)progressBarEnabled
{
    if (_progressBarEnabled == progressBarEnabled) {
        return;
    }
    
    _progressBarEnabled = progressBarEnabled;
    
    if (progressBarEnabled) {
        self.progressView.layer.cornerRadius = kprogressViewRadius;
        CGFloat progressViewY = 41;
        if (self.currentNaviBar.frame.size.height < 10) {
            progressViewY = 0;
        }
        [self.progressView setFrame:CGRectMake(0, progressViewY , CGRectGetWidth(self.view.frame), kprogressViewHeight)];
        self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
        if (self.isAppeared) {
            [_currentNaviBar addSubview:self.progressView];
        }
        _progressBar.progressView = self.progressView;
        
        _progressBar = [[YHWebViewProgress alloc] init];
        _progressBar.progressView = self.progressView;
        
    } else {
        if (self.progressBar) {
            [self.progressBar.progressView removeFromSuperview];
            self.progressBar = nil;
        }
    }
}

- (YHWebViewProgressView *)progressView
{
    static YHWebViewProgressView *sharedProgressViewInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedProgressViewInstance = [[YHWebViewProgressView alloc] init];
    });
    return sharedProgressViewInstance;
}

- (NSMutableArray *)autoSchemes
{
    if (!_autoSchemes) {
        _autoSchemes = [[NSMutableArray alloc] initWithObjects:
                        @"itms-apps",
                        @"itms-appss",
                        @"itmss",
                        @"tel",
                        @"sms",
                        @"mailto",
                        @"yohoefashion4in1",
                        @"yohomars", nil];
    }
    return _autoSchemes;
}

- (NSMutableArray *)autoHosts
{
    if (!_autoHosts) {
        _autoHosts = @[@"itunes.apple.com"].mutableCopy;
    }
    return _autoHosts;
}

- (NSValue *)pointerValue
{
    if (!_pointerValue) {
        _pointerValue = [NSValue valueWithPointer:(__bridge const void *)(self)];
    }
    return _pointerValue;
}

- (NSString*)userAgent
{
    _userAgent = [super userAgent];
    if ([self.delegate respondsToSelector:@selector(extraUserAgent)]) {
        NSString *ua = [self.delegate extraUserAgent];
        if (ua.length) {
            return [NSString stringWithFormat:@"%@ %@", _userAgent, ua];
        }
    }
    return _userAgent;
}

#pragma mark - Public
- (instancetype)initWithUrl:(NSString *)url
{
    self = [self init];
    if (self) {
        self.startPage = url;
    }
    
    return self;
}

- (void)loadWebUrl:(NSString *)urlStr
{
    NSURL *URL = nil;
    if (urlStr.length > 0) {
        URL = [NSURL URLWithString:urlStr];
        if (URL == nil) {
            // 如果url里面含有需要转码的字符,则这里进行一次编码
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            URL = [NSURL URLWithString:urlStr];
        }
    }
    [self loadURL:URL];
}

- (void)loadURL:(NSURL *)URL
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    self.originRequest = request;
    // 系统版本>=11.0 && 当前使用的是WKWebview 则 无需回调
    BOOL needNotDoWillRequestMethod = (YHE_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0")
                                       && [self.webView isKindOfClass:WKWebView.class]);
    if (!needNotDoWillRequestMethod
        && [self.delegate respondsToSelector:@selector(explorerWillLoadRequest:)]) {
        [self.delegate explorerWillLoadRequest:request];
    }
    self.startPage = request.URL.absoluteString;
    [self.webViewEngine loadRequest:request];
}

- (void)loadHTMLString:(NSString *)html
{
    [self.webViewEngine loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

- (void)loadHTMLString:(NSString *)html baseURL:(nullable NSURL *)baseURL
{
    [self.webViewEngine loadHTMLString:html baseURL:baseURL];
}

- (void)setProgressBarColor:(UIColor *)color
{
    if (self.progressBar) {
        YHWebViewProgressView *view = (YHWebViewProgressView *)self.progressBar.progressView;
        view.progressBarColor = color;
    }
}

- (void)registerLinkParser:(id <YHLinkParserDelegate>)parser
{
    if ([self.linkParsers containsObject:parser]) {
        return;
    }
    
    __weak typeof(self)weakSelf = self;
    parser.completion = ^(NSDictionary *result) {
        [weakSelf parseFinishedWithResult:result];
    };
    
    [self.linkParsers addObject:parser];
}

- (void)unRegisterLinkParser:(id <YHLinkParserDelegate>)parser
{
    [self.linkParsers removeObject:parser];
}

#pragma mark - Private
- (void)parseFinishedWithResult:(NSDictionary *)result
{
    if ([self.delegate respondsToSelector:@selector(explorerDidDetectParameters:)])
    {
        [self.delegate explorerDidDetectParameters:result];
    }
    
    if ([self.delegate respondsToSelector:@selector(explorer:didDetectParameters:)]) {
        [self.delegate explorer:self didDetectParameters:result];
    }
}

#pragma mark WKNavigationDelegate implementation
//页面开始加载时调用 1
- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation
{
    [self callback_webViewDidStartLoad];
}

// 页面加载完成之后调用 2
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation
{
    self.originRequest = [NSURLRequest requestWithURL:webView.URL];

    [self callback_webViewDidFinishLoad];
}
// 页面加载失败时调用
- (void)webView:(WKWebView*)theWebView didFailProvisionalNavigation:(WKNavigation*)navigation withError:(NSError*)error
{
    [self callback_webViewDidFailLoadWithError:error];
}
// 数据加载发生错误时调用
- (void)webView:(WKWebView*)theWebView didFailNavigation:(WKNavigation*)navigation withError:(NSError*)error
{
    [self callback_webViewDidFailLoadWithError:error];
}
// 进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    if ([self.progressBar respondsToSelector:@selector(yhExplorer_webViewWebContentProcessDidTerminate:)]){
        [self.progressBar yhExplorer_webViewWebContentProcessDidTerminate:webView];
    }
    [webView reload];
}

//在发送请求之前,决定是否跳转
- (void)webView: (WKWebView *) webView decidePolicyForNavigationAction: (WKNavigationAction*) navigationAction decisionHandler: (void (^)(WKNavigationActionPolicy)) decisionHandler
{
    NSURLRequest *request = navigationAction.request;
    BOOL result = [self callback_webViewShouldStartLoadWithRequest:request navigationType:navigationAction.navigationType];
    if (result) {
        if (YHE_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0")
            && [self.delegate respondsToSelector:@selector(wkwebviewDecidePolicyForNavigationActionWithUrl:)]) {
            [self.delegate wkwebviewDecidePolicyForNavigationActionWithUrl:navigationAction.request.URL];
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    } else {
        decisionHandler(WKNavigationActionPolicyCancel);
    }
}

#pragma mark - WKUIDelegate
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    if (self.isViewLoaded && self.view.window) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认"
                                                            style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction *action) { completionHandler(); }]];
        [self presentViewController:alertController animated:YES completion:^{}];
    } else {
        if (completionHandler) {
            completionHandler();
        }
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
    if (self.isViewLoaded && self.view.window) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction *action) {
                                                              if (completionHandler) {
                                                                  completionHandler(YES);
                                                              }
                                                          }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                            style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction *action) {
                                                              if (completionHandler) {
                                                                  completionHandler(NO);
                                                              }
                                                          }]];
        [self presentViewController:alertController animated:YES completion:^{}];
    } else {
        if (completionHandler) {
            completionHandler(NO);
        }
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
    if (self.isViewLoaded && self.view.window) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = defaultText;
        }];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"完成"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
                                                              if (completionHandler) {
                                                                  completionHandler(alertController.textFields[0].text?:@"");
                                                              }
                                                          }]];
    } else {
        if (completionHandler) {
            completionHandler(@"");
        }
    }
}

#pragma mark - WebViewDelegate Callback
- (void)callback_webViewDidStartLoad
{
    if ([self.progressBar respondsToSelector:@selector(yhExplorer_webViewDidStartLoad:)]) {
        [self.progressBar yhExplorer_webViewDidStartLoad:self];
    }
    [self.commandQueue resetRequestId];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webViewDidStartLoad:)])
    {
        [self.delegate yhExplorer_webViewDidStartLoad:self];
    }
}

- (void)callback_webViewDidFinishLoad
{
    self.failURL = nil;
    if ([self.progressBar respondsToSelector:@selector(yhExplorer_webViewDidFinishLoad:)]) {
        [self.progressBar yhExplorer_webViewDidFinishLoad:self];
    }
    [CDVUserAgentUtil releaseLock:self.userAgentLockToken];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webViewDidFinishLoad:)])
    {
        [self.delegate yhExplorer_webViewDidFinishLoad:self];
    }
}

- (void)callback_webViewDidFailLoadWithError:(NSError *)error
{
    NSString *failingURLString = [error.userInfo objectForKey:NSURLErrorFailingURLStringErrorKey];
    failingURLString = [NSString stringWithFormat:@"%@", failingURLString];
    
    if (error.code == -1009) {
        self.failURL = [NSURL URLWithString:failingURLString];
        [self addRetryButton];
    } else if (error.code >= 500) {
        self.failURL = nil;
        NSString *failDescription = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
        NSMutableDictionary *errorDict = @{}.mutableCopy;
        [errorDict setValue:@(error.code) forKey:@"Code"];
        [errorDict setValue:failDescription forKey:@"Description"];
        [errorDict setValue:failingURLString forKey:@"URL"];
        NSString *message = [NSString stringWithFormat:@"%@", errorDict];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"ERROR" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认"
                                                            style:UIAlertActionStyleCancel
                                                          handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    if ([self.progressBar respondsToSelector:@selector(yhExplorer_webView:didFailLoadWithError:)])
    {
        [self.progressBar yhExplorer_webView:self didFailLoadWithError:error];
    }
    [CDVUserAgentUtil releaseLock:self.userAgentLockToken];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webView:didFailLoadWithError:)])
    {
        [self.delegate yhExplorer_webView:self didFailLoadWithError:error];
    }
}

- (BOOL)callback_webViewShouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(WKNavigationType)navigationType
{
    [self removeRetryButton];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webView:shouldStartLoadWithRequest:navigationType:)])
    {
        if (![self.delegate yhExplorer_webView:self shouldStartLoadWithRequest:request navigationType:navigationType]) {
            return NO;
        }
    }
    
    NSURL *url = [request URL];
    
    /*
     * Execute any commands queued with cordova.exec() on the JS side.
     * The part of the URL after gap:// is irrelevant.
     */
    if ([[url scheme] isEqualToString:@"gap"]) {
        [self.commandQueue fetchCommandsFromJs];
        // The delegate is called asynchronously in this case, so we don't have to use
        // flushCommandQueueWithDelayedJs (setTimeout(0)) as we do with hash changes.
        [self.commandQueue executePending];
        return NO;
    }
    
    if (self.automaticallySchemeHandle) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            NSArray *array = [self.autoSchemes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", url.scheme]];
            if (array.count > 0) {
                [[UIApplication sharedApplication] openURL:url];
                return NO;
            }
            array = [self.autoHosts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", url.host]];
            if (array.count > 0) {
                [[UIApplication sharedApplication] openURL:url];
                return NO;
            }
        }
    }
    
    /*
     * Give plugins the chance to handle the url
     */
    
    if (navigationType == -1)
    {
        navigationType = WKNavigationTypeOther;
    }
    
    BOOL anyPluginsResponded = NO;
    BOOL shouldAllowRequest = NO;
    
    for (NSString* pluginName in self.pluginObjects) {
        CDVPlugin* plugin = [self.pluginObjects objectForKey:pluginName];
        SEL selector = NSSelectorFromString(@"shouldOverrideLoadWithRequest:navigationType:");
        if ([plugin respondsToSelector:selector]) {
            anyPluginsResponded = YES;
            shouldAllowRequest = (((BOOL (*)(id, SEL, id, WKNavigationType))objc_msgSend)(plugin, selector, request, navigationType));
            if (!shouldAllowRequest) {
                break;
            }
        }
    }

    if (anyPluginsResponded) {
        return shouldAllowRequest;
    }
    return YES;
}

#pragma mark - WebViewProtocol

- (UIScrollView *)scrollView
{
    return [self.webView scrollView];
}

- (NSURL *)requestURL
{
    return [self.webViewEngine URL];
}

- (BOOL)isLoading
{
    return [self.webView isLoading];
}

- (BOOL)canGoBack
{
    return [self.webView canGoBack];
}

- (BOOL)canGoForward
{
    return [self.webView canGoForward];
}

- (id)goBack
{
    return [self.webView goBack];
}

- (id)goForward
{
    return [self.webView goForward];
}

- (id)reload
{
    return [self.webView reload];
}

- (id)reloadFromOrigin
{
    return [self.webView loadRequest:self.originRequest];
}

- (void)stopLoading
{
    [self.webView stopLoading];
}

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
{
    [self.webView evaluateJavaScript:javaScriptString completionHandler:completionHandler];
}

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)javaScriptString
{
    __block NSString *result = nil;
    __block BOOL isExecuted = NO;
    [self.webView evaluateJavaScript:javaScriptString completionHandler:^(id obj, NSError* error) {
        result = obj;
        isExecuted = YES;
    }];
    
    while (isExecuted == NO) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
    return result;
}

- (void)yh_setScrollEnabled:(BOOL)enabled
{
    UIView *view = self.webView;
    UIScrollView *scrollView = view.scrollView;
    
    scrollView.scrollEnabled = enabled;
    scrollView.panGestureRecognizer.enabled = enabled;
    
    // There is one subview as of iOS 8.1 of class WKScrollView
    for (UIView* subview in view.subviews) {
        if ([subview respondsToSelector:@selector(setScrollEnabled:)]) {
            [(id)subview setScrollEnabled:enabled];
        }
        
        if ([subview respondsToSelector:@selector(panGestureRecognizer)]) {
            [[(id)subview panGestureRecognizer] setEnabled:enabled];
        }
        
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"title"])
    {
        NSString *title = change[NSKeyValueChangeNewKey];
        _pageTitle = title;
        if (self.delegate && [self.delegate respondsToSelector:@selector(pageTitleUpdated:)]) {
            [self.delegate pageTitleUpdated:title];
        }
    }
}

#pragma mark - CDVYHInterfaceDelegate
- (BOOL)parseLink:(NSString *)linkUrl
{
    for (id <YHLinkParserDelegate> parser in self.linkParsers) {
        if ([parser parseString:linkUrl]) {
            return YES;
        }
    }
    
    return NO;
}

- (void)nativeActionDidTriggerEventWithUserInfo:(NSDictionary *)userInfo completion:(void (^)(id, BOOL))completion {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.delegate respondsToSelector:@selector(didGetMessageFromWeb:completion:)]) {
            [self.delegate didGetMessageFromWeb:userInfo completion:completion];
        }
    });
}

#pragma mark - Method Forwarding
- (BOOL)respondsToSelector:(SEL)aSelector
{
    if ([super respondsToSelector:aSelector]) {
        return YES;
    }
    
    if ([self.webView respondsToSelector:aSelector]) {
        return YES;
    }
    
    return NO;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
    if (!signature) {
        if (self.webView && [self.webView respondsToSelector:aSelector]) {
            return [(NSObject *)self.webView methodSignatureForSelector:aSelector];
        }
    }
    
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    if (self.webView && [self.webView respondsToSelector:[anInvocation selector]]) {
        [anInvocation invokeWithTarget:self.webView];
    }
}

#pragma mark - Getter Method

- (UIButton *)retryButton
{
    if (!_retryButton) {
        _retryButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _retryButton.frame = self.webView.bounds;
        _retryButton.backgroundColor = UIColor.whiteColor;
        [_retryButton setImage:[UIImage imageNamed:@"yh_explorer_refresh_icon"] forState:UIControlStateNormal];
        [_retryButton setImage:[UIImage imageNamed:@"yh_explorer_refresh_icon"] forState:UIControlStateHighlighted];
        [_retryButton addTarget:self action:@selector(retryAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _retryButton;
}

- (void)retryAction:(id)sender
{
    if (!self.isLoading) {
        if (self.failURL) {
            [self.webViewEngine loadRequest:[NSURLRequest requestWithURL:self.failURL]];
        } else {
            if (![self checkAndReinitViewUrl]) {
                [self reloadFromOrigin];
            }
        }
    }
    self.failURL = nil;
}

- (void)addRetryButton
{
    self.retryButton.center = self.view.center;
    [self.view addSubview:self.retryButton];
    [self.view bringSubviewToFront:self.retryButton];
}

- (void)removeRetryButton
{
    if ([self.retryButton superview]) {
        [self.retryButton removeFromSuperview];
    }
}

@end


@implementation YHExplorerCommandDelegate

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString*)className
{
    return [super getCommandInstance:className];
}

- (NSString*)pathForResource:(NSString*)resourcepath
{
    return [super pathForResource:resourcepath];
}

@end

@implementation YHExplorerCommandQueue

- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

@end