//
//  RNPhotoEditer.m
//  RNPhotoEditor
//
//  Created by Hanson on 2019/6/28.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "RNPhotoEditer.h"
#import "UIView+Frame.h"
#import "UIImage+Extenstion.h"
#import "PEMarkView.h"

// iPhoneX 屏幕尺寸判断
#define YBF_IphoneX [UIScreen mainScreen].bounds.size.height > 736
// iPhoneX 底部 home 键位置预留
#define  YBF_TabbarSafeBottomMargin   (YBF_IphoneX ? 0.f : 0.f)
#define  YBF_TabbarSafeTopMargin   (YBF_IphoneX ? 10.f : 0.f)
#define screenW ([[UIScreen mainScreen] bounds].size.width)
#define screenH ([[UIScreen mainScreen] bounds].size.height)
#define fontSize (YBF_IphoneX ? 20.f : 18.f)
@interface RNPhotoEditer()

@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIButton *finishButton;
@property (strong, nonatomic) UIButton *cancleButton;

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UIScrollView *bottomView;
@property (strong, nonatomic) UIButton *firstMarkBtn;

@property (strong, nonatomic) PEMarkView *markView;
@property (assign, nonatomic) CGFloat blurValue;

@end

@implementation RNPhotoEditer

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        self.blurValue = 0;
        self.backgroundColor = [UIColor whiteColor];
        self.bottomView.backgroundColor = [UIColor clearColor];
    }
    return self;
}


- (void)setupUI {
    
    [self addSubview:self.imageView];
    [self addSubview:self.bottomView];
    [self addSubview:self.cancleButton];
    [self addSubview:self.finishButton];
    [self addSubview:self.titleLabel];
    [self.imageView addSubview:self.markView];
//    [self getImageWithSize:CGSizeMake(20, 20) color:UIColor.blackColor];
    
    self.finishButton.titleLabel.font = [UIFont systemFontOfSize:fontSize - 4];
    self.cancleButton.titleLabel.font = self.finishButton.titleLabel.font;
    [self.finishButton addTarget:self action:@selector(finishEdit) forControlEvents:UIControlEventTouchUpInside];
    [self.cancleButton addTarget:self action:@selector(cancelEdit) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initMarkButton {
    for(UIView *view in self.bottomView.subviews) {
        if(![view isKindOfClass:[UIButton class]]) {continue;}
        
        [view removeFromSuperview];
    }
    
    self.firstMarkBtn = [self createButtonWithImage:self.editImage];
    [self.bottomView addSubview:self.firstMarkBtn];
    for (NSInteger i = 0; i < self.markImages.count; i++) {
        [self.bottomView addSubview:[self createButtonWithImage:self.markImages[i]]];
    }
}

- (UIButton *)createButtonWithImage:(UIImage *)image {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addMarkImage:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor colorWithWhite:0.93 alpha:1];
    button.layer.cornerRadius = 5;
    button.layer.masksToBounds = YES;
    return button;
}

- (void)addMarkImage:(UIButton *)button {
    UIImage *image = [button currentImage];
    // 第一张模糊
    if ([image isEqual:self.editImage]) {
        self.blurValue += 20;
        // 点击模糊3次，第4次变原图
        if(self.blurValue > 60) {
            self.blurValue = 0;
            self.imageView.image = self.editImage;
            return;
        }
        self.imageView.image = [self.editImage gaussianBlurWithValue:self.blurValue];
        return;
    }
    [self.markView addMarkImage:image];
}



- (void)setSource:(NSString *)source {
    // Process Image for Editing
    _source = source;
    UIImage *editImage = [self getImageWithPath:source];
//    NSLog(@"lovemaker photoEditor, set source %@, find image %@", source, editImage);
    if(!editImage && self.onCancel) {
        self.onCancel(@{@"result":@"资源文件不存在"});
        return;
    }
    
    self.editImage = editImage;
    [self cleanAllOpration];
}

- (void)setMarks:(NSArray *)marks {
    _marks = marks;
    
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *path in marks) {
        UIImage *markImage = [self getImageWithPath:path];
        if (!markImage) { continue; }
        [array addObject:markImage];
    }
    self.markImages = array;
//    NSLog(@"lovemaker photoEditor, input marks %@, find images %@", marks, array);
    
    [self initMarkButton];
    [self layoutSubviews];
}

- (UIImage *)getImageWithPath:(NSString *)path {
    
    UIImage *image = nil;
    // 如果path是绝对路径
    image = [UIImage imageWithContentsOfFile:path];
    if (!image) {
        // 判断是否是图片名
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:path ofType:nil];
        if (imagePath) {
            image = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    
//#ifdef DEBUG
    //  走开发罗辑
    if (image == nil) {
        NSURL *url = [NSURL URLWithString:path];
        NSData *data = [NSData dataWithContentsOfURL:url];
        image = [UIImage imageWithData:data];
    }
//#endif
    return image;
}

- (void)setEditImage:(UIImage *)editImage {
    _editImage = editImage;
    self.imageView.image = editImage;
    if(self.firstMarkBtn) {
        [self.firstMarkBtn setImage:editImage forState:UIControlStateNormal];
    }
}


#pragma mark - 图片合成

- (void)cleanAllOpration {
    self.blurValue = 0;
    [self.markView cleanMarkImage];
    self.imageView.image = self.editImage;
}

- (void)finishEdit {
    [self.markView endMarkEdit];
    UIImage *resultImage = [self getImageInView:self.imageView];
    NSString *imagePath = [resultImage saveToDevice];
    
    if(self.onComplete) {
        self.onComplete(@{@"uri":imagePath});
    }
}

- (void)clear {
    [UIImage cleanTempImages];
}

- (void)cancelEdit {
    [self cleanAllOpration];
    
    if(self.onCancel) {
        self.onCancel(nil);
    }
}

// 截屏
- (UIImage *)getImageInView:(UIView *)view {
    
    UIGraphicsBeginImageContext(view.bounds.size);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGFloat imgW = ((UIImageView *)view).image.size.width;
    CGFloat imgH = ((UIImageView *)view).image.size.height;
    CGFloat ratW = view.frame.size.width / imgW;
    CGFloat ratH = view.frame.size.height / imgH;
    CGRect realRect = view.bounds;
    if(ratW > ratH) {
        realRect.size.width = imgH * ratH;
        realRect.origin.x = (view.width - realRect.size.width) * 0.5;
    } else {
        realRect.size.height =  imgH * ratW;
        realRect.origin.y = (view.height - realRect.size.height) * 0.5;
    }
    CGImageRef cgimage = CGImageCreateWithImageInRect(image.CGImage, realRect);
    return [UIImage imageWithCGImage:cgimage];
}

#pragma mark - layout
- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat buttonHeight = 44;
    
    [self.titleLabel sizeToFit];
    self.titleLabel.height = buttonHeight;
    self.titleLabel.centerX = self.width * 0.5;
    self.titleLabel.top = 20 + YBF_TabbarSafeTopMargin;
    
    self.bottomView.width = self.width;
    self.bottomView.height = 80;
    self.bottomView.bottom = self.height - 20 - YBF_TabbarSafeBottomMargin;
    
    self.imageView.top = 64 + YBF_TabbarSafeTopMargin;
    self.imageView.height = self.bottomView.top - 20 - self.imageView.top;
    self.imageView.width = self.width;
    self.markView.frame = self.imageView.bounds;
    
    CGFloat buttonWidh = self.width / 4;
    CGFloat buttonMargin = 20;
    NSInteger i = 0;
    for (UIButton *button in self.bottomView.subviews) {
        if(![button isKindOfClass:[UIButton class]]) {continue;}
        
        button.height = self.bottomView.height;
        button.width = button.height;
        button.x = i * buttonWidh + buttonMargin;
        i++;
    }
    self.bottomView.contentSize = CGSizeMake(buttonWidh * i + buttonMargin * 2, self.bottomView.height);
    
    self.cancleButton.height = buttonHeight;
    self.cancleButton.width = 60;
    self.cancleButton.top = self.titleLabel.top;
    
    self.finishButton.frame = self.cancleButton.frame;
    self.finishButton.right = self.width;
}


#pragma mark - lazy

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.userInteractionEnabled = YES;
        _imageView.backgroundColor = [UIColor colorWithWhite:0.93 alpha:1];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _imageView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIScrollView alloc] init];
        _bottomView.scrollEnabled = YES;
        _bottomView.showsHorizontalScrollIndicator = NO;
//        _bottomView.delegate = self;
    }
    return _bottomView;
}

- (PEMarkView *)markView {
    if (!_markView) {
        _markView = [[PEMarkView alloc] init];
    }
    return _markView;
}

- (UIButton *)cancleButton {
    if (!_cancleButton) {
        _cancleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        UIColor *color = [UIColor colorWithRed:0.176 green:0.196 blue:0.251 alpha:1];
        CALayer *layer = [self getBackLayerForSize:CGSizeMake(10, 18) color:color];
        layer.frame = CGRectMake(15, 14, 10, 18);
        [_cancleButton.layer addSublayer:layer];
    }
    return _cancleButton;
}

- (void)setTitle:(NSString *)title {
    _title = title;
    self.titleLabel.text = title;
}

- (UIButton *)finishButton {
    if (!_finishButton) {
        _finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_finishButton setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [_finishButton setTitle:@"确认" forState:UIControlStateNormal];
    }
    return _finishButton;
}

- (CALayer *)getBackLayerForSize:(CGSize)size color:(UIColor *)color {
    UIBezierPath *polygonPath = [UIBezierPath bezierPath];
    
    // 这些点的位置都是相对于所在视图的
    // 起点
    [polygonPath moveToPoint:CGPointMake(size.width, 0)];
    // 其他点
    [polygonPath addLineToPoint:CGPointMake(0, size.height * 0.5)];
    [polygonPath addLineToPoint:CGPointMake(size.width, size.height)];
    
    
    CAShapeLayer *polygonLayer = [CAShapeLayer layer];
    polygonLayer.lineWidth = 2;
    polygonLayer.strokeColor = color.CGColor;
    polygonLayer.path = polygonPath.CGPath;
    polygonLayer.fillColor = nil; // 默认为blackColor
    return polygonLayer;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont boldSystemFontOfSize:fontSize];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.text = @"编辑图片";
    }
    return _titleLabel;
}
@end
