//
//  DKWIFIVideoView.m
//  Pods
//
//  Created by nana on 2020/7/1.
//

#import "DKWIFIVideoView.h"



@interface DKWIFIVideoView()<WKNavigationDelegate>

@property(nonatomic, assign)NSTimeInterval lastReceiveImageTime;
@property(nonatomic, strong)dispatch_source_t gcdTimer;
@end

@implementation DKWIFIVideoView

- (instancetype)init {
    if (self = [super init]) {
        self.webView = [[WKWebView alloc]init];
        self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.webView.navigationDelegate = self;
        [self addSubview:self.webView];
        self.layer.masksToBounds = YES;
        @weakify(self);
          _gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
          dispatch_source_set_timer(_gcdTimer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
          dispatch_source_set_event_handler(_gcdTimer, ^{
              @strongify(self);
              NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
              if (nowTime-self.lastReceiveImageTime > 5) {
                  dispatch_sync(dispatch_get_main_queue(), ^{
                      if (!self.videoUrl) {
                            self.videoUrl = @"http://192.168.168.1:8888/?action=stream";
                        }
                        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.videoUrl]];
                      [self.webView loadRequest:req];;
                  });
                  self.lastReceiveImageTime = nowTime;
              }
          });

          dispatch_resume(_gcdTimer);
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGSize sSize = self.frame.size;
    if (sSize.width > sSize.height) {
        CGFloat h = sSize.width/1280*720;
        self.webView.frame = CGRectMake(0,(sSize.height-h)/2,sSize.width,h);
    }else {
        CGFloat w = sSize.height/720*1280;
        self.webView.frame = CGRectMake((sSize.width-w)/2,0,w, self.frame.size.height);
    }

}

- (UIImage *)captureImage {
    UIGraphicsBeginImageContextWithOptions(self.webView.bounds.size, self.opaque, 0);
    [self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGRect irect = CGRectZero;
    CGSize sSize = self.frame.size;
    if (sSize.width > sSize.height) {
        CGFloat h = sSize.width/1280*720;
        irect = CGRectMake(0, (self.frame.size.width-h)/2,  self.frame.size.width,  self.frame.size.height);
    }else {
         CGFloat w = self.frame.size.height/720*1280;
         irect = CGRectMake((w-self.frame.size.width)/2, 0,  self.frame.size.width,  self.frame.size.height);
    }
    return [self imageByCropToRect:irect image:snap];
}

- (UIImage *)imageByCropToRect:(CGRect)rect image:(UIImage *)image {
    rect.origin.x *= image.scale;
    rect.origin.y *= image.scale;
    rect.size.width *= image.scale;
    rect.size.height *= image.scale;
    if (rect.size.width <= 0 || rect.size.height <= 0) return nil;
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *rimage = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return rimage;
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
       decisionHandler(WKNavigationResponsePolicyAllow);
    self.lastReceiveImageTime = [[NSDate date] timeIntervalSince1970];

}

@end
