//
//  LSExtractaView.m
//  LSColorExtracta
//
//  Created by Dylan on 2018/11/7.
//  Copyright © 2018 Yang. All rights reserved.
//

#import "LSExtractaView.h"
#import "LSCircleView.h"

#define screenWidth [[UIScreen mainScreen] bounds].size.width

@interface LSExtractaView ()

@property (nonatomic, strong)LSCircleView* circleView;
@property (nonatomic, strong)UIImage* windowImage;

@end

@implementation LSExtractaView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        self.clipsToBounds = YES;
        [self addSubview:self.circleView];
        
        int64_t delayInSeconds = 10.0;      // 延迟的时间
        /*
         *@parameter 1,时间参照，从此刻开始计时
         *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
         */
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            // do something
            UIColor* color = [self colorFromPoint:self.circleView.center capture:YES];
            [self.circleView setBackgroundColor:color];
        });
    }
    return self;
}

- (LSCircleView*)circleView {
    if (!_circleView) {
        _circleView = [[LSCircleView alloc]init];
        _circleView.frame = CGRectMake(0, 0, 40, 40);
        _circleView.center = CGPointMake(screenWidth/2, 100);
        
    }
    return _circleView;
}

// 一根或者多根手指开始触摸view（手指按下）
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {
    CGPoint point = [self pointFormTouches:touches];
    UIColor* color = [self colorFromPoint:point capture:YES];
    [self.circleView styleCenter:point style:StyleTypeCircle color:color];
}

//  一根或者多根手指在view上移动（随着手指的移动，会持续调用该方法）
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint point = [self pointFormTouches:touches];
    UIColor* color = [self colorFromPoint:point capture:NO];
    self.circleView.center = point;
    [self.circleView styleCenter:point style:StyleTypeCircle color:color];
}

// 一根或者多根手指离开view（手指抬起）
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint point = [self pointFormTouches:touches];
    UIColor* color = [self colorFromPoint:point capture:NO];
    [self.circleView styleCenter:point style:StyleTypeRound color:color];
}


-(CGPoint)pointFormTouches:(NSSet *)touches {
    UITouch* touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    if (point.x < 0){
        point.x = 0;
    }
    
    if (point.y < 0){
        point.y = 0;
    }
    
    if (point.x > self.frame.size.width){
        point.x = self.frame.size.width;
    }
    
    if (point.y > self.frame.size.height){
        point.y = self.frame.size.height;
    }
    
    return point;
}


- (UIColor *)colorFromPoint:(CGPoint)point capture:(BOOL)capture {
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(capture){
        // 截屏
        UIGraphicsBeginImageContext(window.frame.size);//全屏截图，包括window
        [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        self.windowImage = UIGraphicsGetImageFromCurrentImageContext();
    }
    
    UIImage *windowImage = self.windowImage;
    // 控件的的中心点转成相对于屏幕的点
    CGPoint cEPoint = [self convertPoint:point toView:window];
    
    // 如果点超出图像范围，则退出
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, windowImage.size.width, windowImage.size.height), cEPoint)) {
        return nil;
    }
    
    NSInteger pointX = trunc(cEPoint.x);
    NSInteger pointY = trunc(cEPoint.y);
    CGImageRef cgImage = windowImage.CGImage;
    NSUInteger width = windowImage.size.width;
    NSUInteger height = windowImage.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = { 0, 0, 0, 0 };
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    
    // Draw the pixel we are interested in onto the bitmap context
    CGContextTranslateCTM(context, -pointX, pointY-(CGFloat)height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, (CGFloat)width, (CGFloat)height), cgImage);
    CGContextRelease(context);
    
    //    // 把[0,255]的颜色值映射至[0,1]区间
    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;
    
    
    UIColor* color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    return color;
    
    //    NSNumber* red   = [NSNumber numberWithFloat:(CGFloat)pixelData[0]];
    //    NSNumber* green = [NSNumber numberWithFloat:(CGFloat)pixelData[1]];
    //    NSNumber* blue  = [NSNumber numberWithFloat:(CGFloat)pixelData[2]];
    //    NSNumber* alpha = [NSNumber numberWithFloat:(CGFloat)pixelData[3]];
    //    NSDictionary* rgba = @{@"r": red,@"g": green,@"b": blue,@"a": alpha,};
    //
    //    return rgba;
}



@end

