




#import "ACBridgeWebView.h"
#import "ACJSImplement.h"

@interface ACBridgeWebView () <UIWebViewDelegate>

@property (nonatomic, weak) id<UIWebViewDelegate> outsideDelegate;
// webView Bridge处理
@property (nonatomic, strong) ACJSImplement *jsImplement;

@end

@implementation ACBridgeWebView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initDelegate];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initDelegate];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    
    if (self){
        [self initDelegate];
    }
    
    return self;
}

- (void)initDelegate
{
    [super setDelegate:self];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([self.jsImplement handleAppCoreURL:[request URL]] == NO) {
        return NO;
    }
    
    if (self.outsideDelegate && self.outsideDelegate != self && [self.outsideDelegate respondsToSelector:_cmd]) {
        return [self.outsideDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    else {
        return YES;
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if (self.outsideDelegate && self.outsideDelegate != self && [self.outsideDelegate respondsToSelector:_cmd]) {
        [self.outsideDelegate webViewDidStartLoad:webView];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (self.outsideDelegate && self.outsideDelegate != self && [self.outsideDelegate respondsToSelector:_cmd]) {
        [self.outsideDelegate webView:webView didFailLoadWithError:error];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.jsImplement injectPluginJS];
    [self.jsImplement injectWebPlusJS];

    if (self.outsideDelegate && self.outsideDelegate != self && [self.outsideDelegate respondsToSelector:_cmd]) {
        [self.outsideDelegate webViewDidFinishLoad:webView];
    }
}

#pragma mark - getter and setter

- (void)setVc:(UIViewController *)vc
{
    _vc = vc;
    self.jsImplement.vc = vc;
}

- (void)setDelegate:(id<UIWebViewDelegate>)delegate
{
    self.outsideDelegate = delegate;
}

- (id<UIWebViewDelegate>)delegate
{
    return self.outsideDelegate;
}

- (ACJSImplement *)jsImplement
{
    if (_jsImplement == nil) {
        _jsImplement = [[ACJSImplement alloc] init];
        _jsImplement.webView = self;
        _jsImplement.vc = self.vc;
    }
    return _jsImplement;
}

@end
