//
//  SignatureDrawingView.m
//  UberSignature
//
//  Created by robin on 2019/1/23.
//  Copyright © 2019年 Uber. All rights reserved.
//

#import "SignatureDrawingView.h"
#import "UBSignatureDrawingModelAsync.h"


@interface SignatureDrawingView ()

@property (nonatomic) BOOL isEmpty;

@property (nonatomic, readonly) UBSignatureDrawingModelAsync *model;
@property (nonatomic, readonly) NSOperationQueue *modelOperationQueue;
@property (nonatomic) CAShapeLayer *bezierPathLayer;

@property (nonatomic) UIImageView *imageView;

@property (nonatomic) UIImage *presetImage;

@end

@implementation SignatureDrawingView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithImage:(UIImage *)image {
    
    CGSize size = [UIScreen mainScreen].bounds.size;
    if (self = [super initWithFrame:CGRectMake(0, 0, size.width, size.height)]) {
        _presetImage = image;
        _isEmpty = (!image);
        
        _model = [[UBSignatureDrawingModelAsync alloc] init];
        self.model.imageSize = self.bounds.size;
        [self _updateLineAttrubites];
        
        self.backgroundColor = [UIColor clearColor];
        self.imageView = [[UIImageView alloc] init];
        [self addSubview:self.imageView];
        
        self.bezierPathLayer = ({
            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
            layer.strokeColor = self.signatureColor.CGColor;
            layer.fillColor = self.signatureColor.CGColor;
            layer;
        });
        [self.layer addSublayer:self.bezierPathLayer];
        
        // Constraints
        self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addConstraints:@[
                               [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:0],
                               [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0],
                               [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0],
                               [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1 constant:0]
                               ]];
        
        [self _updateViewFromModel];
    }
    
    return self;
}

-(void)layoutSubviews{
  self.model.imageSize = self.bounds.size;
  [self _updateViewFromModel];
}


#pragma mark - Public

- (void)reset
{
    [self.model reset];
    [self _updateViewFromModel];
}

- (UIImage *)fullSignatureImage
{
    return [self.model fullSignatureImage];
}

- (UIColor *)signatureColor
{
    return self.model.signatureColor;
}

- (void)setSignatureColor:(UIColor *)signatureColor
{
    self.model.signatureColor = signatureColor;
    self.bezierPathLayer.strokeColor = self.signatureColor.CGColor;
    self.bezierPathLayer.fillColor = self.signatureColor.CGColor;
}

- (void)setIsEmpty:(BOOL)isEmpty
{
    if (self.isEmpty == isEmpty) {
        return;
    }
    
    _isEmpty = isEmpty;
}

- (void)setMinLineWidth:(NSInteger)minLineWidth {
    
    _minLineWidth = minLineWidth;
    [self _updateLineAttrubites];
}

- (void)setMaxLineWidth:(NSInteger)maxLineWidth {
    
    _maxLineWidth = maxLineWidth;
    [self _updateLineAttrubites];
}

- (void)_updateLineAttrubites {
    [self.model setLineAttrubites:@{
                                    @"minLineWidth": @(self.minLineWidth > 0 ? self.minLineWidth : 3),
                                    @"maxLineWidth": @(self.maxLineWidth > 0 ? self.maxLineWidth : 7),
                                    }];
}

- (void)_updateViewFromModel
{
    [self.model asyncGetOutputWithBlock:^(UIImage *signatureImage, UIBezierPath *temporarySignatureBezierPath) {
        if (self.imageView.image != signatureImage) {
            self.imageView.image = signatureImage;
        }
        if (!CGPathEqualToPath(self.bezierPathLayer.path, temporarySignatureBezierPath.CGPath)) {
            self.bezierPathLayer.path = temporarySignatureBezierPath.CGPath;
        }
        
        self.isEmpty = (self.bezierPathLayer.path == nil && self.imageView.image == nil);
    }];
}


#pragma mark - UIResponder

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    [self _updateModelWithTouches:touches endContinuousLine:YES];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    
    [self _updateModelWithTouches:touches endContinuousLine:NO];
}

#pragma mark - Private

- (void)_updateModelWithTouches:(NSSet<UITouch *> *)touches endContinuousLine:(BOOL)endContinuousLine
{
    CGPoint touchPoint = [self.class _touchPointFromTouches:touches];
    
    if (endContinuousLine) {
        [self.model asyncEndContinuousLine];
    }
    [self.model asyncUpdateWithPoint:touchPoint];
    
    [self _updateViewFromModel];
}


#pragma mark - Helpers

+ (CGPoint)_touchPointFromTouches:(NSSet<UITouch *> *)touches
{
    UITouch *touch = [touches anyObject];
    
    return [touch locationInView:touch.view];
}

@end
