//
//  RNImageUtil.m
//  BabyBath
//
//  Created by Chung Johnny on 18/1/17.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "RNImageUtil.h"
#import <React/RCTBridge.h>
#import <React/RCTUIManager.h>
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
#import <React/UIView+React.h>
#import <CoreGraphics/CGGeometry.h>



@implementation RNImageUtil

RCT_EXPORT_MODULE();
@synthesize bridge = _bridge;

- (dispatch_queue_t)methodQueue
{
	return self.bridge.uiManager.methodQueue;
}

RCT_EXPORT_METHOD(screenshot:(float)fromx fromy:(float)fromy tox:(float)width toy:(float)height callback:(nonnull RCTResponseSenderBlock)callback){
  dispatch_async(dispatch_get_main_queue(),^{
  CGSize imageSize = CGSizeZero;
  UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  if (UIInterfaceOrientationIsPortrait(orientation)) imageSize = [UIScreen mainScreen].bounds.size;
  else imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
  
  UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  CGContextRef context = UIGraphicsGetCurrentContext();
  for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, window.center.x, window.center.y);
    CGContextConcatCTM(context, window.transform);
    CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
    if (orientation == UIInterfaceOrientationLandscapeLeft) {
      CGContextRotateCTM(context, M_PI_2);
      CGContextTranslateCTM(context, 0, -imageSize.width);
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {
      CGContextRotateCTM(context, -M_PI_2);
      CGContextTranslateCTM(context, -imageSize.height, 0);
    } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
      CGContextRotateCTM(context, M_PI);
      CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
    }
    if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
      [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
    } else {
      [window.layer renderInContext:context];
    }
    CGContextRestoreGState(context);
  }
  UIImage *full_image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
    
    CGRect rect = CGRectMake(fromx, fromy, width, height);
    CGImageRef imageRefRect =CGImageCreateWithImageInRect(full_image.CGImage, rect);
    
    UIImage *image = [[UIImage alloc] initWithCGImage:imageRefRect];
  
  
  static NSDateFormatter *dateFormatter = nil;
  if (dateFormatter == nil) {
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"Y-MM-d HH-mm-ss-SSS"];
  }
  
  NSString *imageFileName = [NSString stringWithFormat:@"%@.png", [dateFormatter stringFromDate:[NSDate date]]];
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,                                                                          NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imageFileName];
  [[NSFileManager defaultManager] createFileAtPath:imagePath contents:UIImagePNGRepresentation(image) attributes:nil];
    NSString *uri = [NSString stringWithFormat:@"file://%@", imagePath];
  callback(@[[NSNull null], imagePath]);
  });
}


@end
