//
//  RNPDFView.m
//  App
//
//  Created by Sibelius Seraphini on 3/1/16.
//  Copyright © 2016 Facebook. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>

#import <React/RCTBridgeModule.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTLog.h>

#import "RNPDFView.h"
#import "PDFView.h"
@implementation RNPDFView {

    UIWebView *webView;
    UIScrollView *scrollView;
    int totalPages;
    UIView *pdfBgView;
    CGFloat maxWidth;
    PDFView *pdfViewEnd;
    CGFloat minScale;
    CGSize viewSize;
}

- (instancetype)init
{
  if ((self = [super init])) {
      scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
      scrollView.delegate = self;
      [self addSubview:scrollView];
  }
  
  return self;
}


- (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath{
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO);
    CFRelease(path);
    document = CGPDFDocumentCreateWithURL(url);
    CFRelease(url);
    totalPages = CGPDFDocumentGetNumberOfPages(document);
    if (totalPages == 0) {
        NSLog(@"%@ has no valid pages!", aFilePath);
        return NULL;
    }
    
    return document;
}

- (void)setPath:(NSString *)path
{
    if (![path isEqual:_path]) {
        _path = [path copy];
        
        CGPDFDocumentRef pdf = [self createPDFFromExistFile:self.path];
        
        pdfBgView = [[UIView alloc]init];
        pdfBgView.backgroundColor = [UIColor whiteColor];
        CGFloat startY = 0;
        maxWidth = 0;
        for (int i=0; i<totalPages; i++) {
            CGPDFPageRef page = CGPDFDocumentGetPage(pdf, i+1);
            CGRect mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
            
            PDFView *pdfView = [[PDFView alloc] initWithFrame:CGRectMake(0, startY, mediaBox.size.width, mediaBox.size.height)];
            pdfView.pdf = pdf;
            pdfView.page = page;
            [pdfBgView addSubview:pdfView];
            
            startY += mediaBox.size.height;
            if (mediaBox.size.width > maxWidth) {
                maxWidth = mediaBox.size.width;
            }
            
            if(i == totalPages-1)
            {
                pdfViewEnd = pdfView;
            }
        }
        viewSize = CGSizeMake(maxWidth, startY);
        pdfBgView.frame = CGRectMake(0, 0, maxWidth, startY);
        scrollView.contentSize = pdfBgView.bounds.size;
    }
}


- (void)reloadPdf
{
    if (self.path == (id)[NSNull null] || self.path.length == 0) {
        return;
    }
    minScale = self.bounds.size.width/maxWidth;
    scrollView.minimumZoomScale = minScale;
    scrollView.maximumZoomScale = 5;
    [scrollView addSubview:pdfBgView];
    [scrollView setZoomScale:self.bounds.size.width/maxWidth];
    
}

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

-(void)addWaterMask:(NSArray*)imgs
{
    pdfViewEnd.imgs = imgs;
    [pdfViewEnd reloadView];
//    [self performSelector:@selector(screenShotAction) withObject:self afterDelay:1.0];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return pdfBgView;
}

-(void)screenShotAction
{
    UIImage* image =nil;
    
    UIGraphicsBeginImageContextWithOptions(viewSize,NO,0.0);
    {
        [pdfBgView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image= UIGraphicsGetImageFromCurrentImageContext();
    }
    
    UIGraphicsEndImageContext();
    //写入相册
//    UIImageWriteToSavedPhotosAlbum(image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
}

#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    
}

@end
