//
//  ImageUtil.m
//  kneet2
//
//  Created by Jason Lee on 10/15/15.
//  Copyright © 2015 ntels. All rights reserved.
//
#import "CommonUtil.h"
#import "ImageUtil.h"

@interface ImageUtil () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    UIImagePickerController *_imagePickerController;
    UIAlertController *_alertController;
}

@end

@implementation ImageUtil


#pragma mark - Graphic Util

+ (UIImage *)imageWithColor:(UIColor *)color height:(CGFloat)height {
    //    CGRect appFrame = [UIScreen mainScreen].applicationFrame;
    
    CGFloat y = 0;// appFrame.origin.y > 20 ? 20 : 0;
    CGRect rect = CGRectMake(0.0f, y, 1.0f, height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


+ (CGFloat)getImageAspectRatio:(UIImage *)image {
    return image.size.width / image.size.height;
}
//해당 이미지를 주어진 크키에 맞추어 리사이즈하여 반환함.
//resize image
+ (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth height:(float)resizeHeight {
    UIGraphicsBeginImageContext(CGSizeMake(resizeWidth, resizeHeight));
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, resizeHeight);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CGContextDrawImage(context, CGRectMake(0.0, 0.0, resizeWidth, resizeHeight), [image CGImage]);
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


+ (UIImage *)resizeImage:(UIImage *)image width:(float)resizeWidth {
    
    float ratio = [ImageUtil getImageAspectRatio:image];
    float resizeHeight = resizeWidth / ratio;
    
    return [ImageUtil resizeImage:image width:resizeWidth height:resizeHeight];
}


+ (UIImage *)resizeImage:(UIImage *)image height:(float)resizeHeight {
    
    float ratio = [ImageUtil getImageAspectRatio:image];
    float resizeWidth = resizeHeight * ratio;
    
    return [ImageUtil resizeImage:image width:resizeWidth height:resizeHeight];
}

+ (CGRect)convertCropRect:(CGRect)cropRect image:(UIImage *)image  {
    UIImage *originalImage = image;
    
    CGSize size = originalImage.size;
    CGFloat x = cropRect.origin.x;
    CGFloat y = cropRect.origin.y;
    CGFloat width = cropRect.size.width;
    CGFloat height = cropRect.size.height;
    UIImageOrientation imageOrientation = originalImage.imageOrientation;
    if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
        cropRect.origin.x = y;
        cropRect.origin.y = size.width - cropRect.size.width - x;
        cropRect.size.width = height;
        cropRect.size.height = width;
    } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
        cropRect.origin.x = size.height - cropRect.size.height - y;
        cropRect.origin.y = x;
        cropRect.size.width = height;
        cropRect.size.height = width;
    } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
        cropRect.origin.x = size.width - cropRect.size.width - x;
        cropRect.origin.y = size.height - cropRect.size.height - y;
    }
    
    return cropRect;
}

+ (UIImage *)croppedImage:(CGRect)cropRect image:(UIImage *)image {
    CGImageRef croppedCGImage = CGImageCreateWithImageInRect(image.CGImage ,cropRect);
    UIImage *croppedImage = [UIImage imageWithCGImage:croppedCGImage scale:1.0f orientation:image.imageOrientation];
    CGImageRelease(croppedCGImage);
    
    return croppedImage;
}

+ (UIImage *)resizeImage:(UIImage *)image size:(CGSize)size imageOrientation:(UIImageOrientation)imageOrientation {
    
    if (size.width > image.size.width) {
        size.width = image.size.width;
    }
    
    if (size.height > image.size.height) {
        size.height = image.size.height;
    }
    
    CGSize imageSize = image.size;
    CGFloat horizontalRatio = size.width / imageSize.width;
    CGFloat verticalRatio = size.height / imageSize.height;
    CGFloat ratio = MIN(horizontalRatio, verticalRatio);
    CGSize targetSize = CGSizeMake(imageSize.width * ratio, imageSize.height * ratio);
    
    UIGraphicsBeginImageContextWithOptions(size, YES, 1.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextScaleCTM(context, 1.0f, -1.0f);
    CGContextTranslateCTM(context, 0.0f, -size.height);
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    if (imageOrientation == UIImageOrientationRight || imageOrientation == UIImageOrientationRightMirrored) {
        transform = CGAffineTransformTranslate(transform, 0.0f, size.height);
        transform = CGAffineTransformRotate(transform, -M_PI_2);
    } else if (imageOrientation == UIImageOrientationLeft || imageOrientation == UIImageOrientationLeftMirrored) {
        transform = CGAffineTransformTranslate(transform, size.width, 0.0f);
        transform = CGAffineTransformRotate(transform, M_PI_2);
    } else if (imageOrientation == UIImageOrientationDown || imageOrientation == UIImageOrientationDownMirrored) {
        transform = CGAffineTransformTranslate(transform, size.width, size.height);
        transform = CGAffineTransformRotate(transform, M_PI);
    }
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(context, CGRectMake((size.width - targetSize.width) / 2, (size.height - targetSize.height) / 2, targetSize.width, targetSize.height), image.CGImage);
    
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}

+ (UIImage*)getMaskedImageWithSourchImage:(UIImage *)srcImage andMaskImage:(UIImage *)maskImage {
    
    CGImageRef maskRef = maskImage.CGImage;
    
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);
    
    CGImageRef masked = CGImageCreateWithMask([srcImage CGImage], mask);
    CGImageRelease(mask);
    
    UIImage *imageMask = [UIImage imageWithCGImage:masked];
    CGImageRelease(masked);
    
    return imageMask;
}

+ (UIImage *)imageToGrayScale:(UIImage *)image {
    if (!image)
        return nil;
    
    int kRed = 1;
    int kGreen = 2;
    int kBlue = 4;
    
    int colors = kGreen | kBlue | kRed;
    int m_width = image.size.width;
    int m_height = image.size.height;
    
    uint32_t *rgbImage = (uint32_t *) malloc(m_width * m_height * sizeof(uint32_t));
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImage, m_width, m_height, 8, m_width * 4, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetShouldAntialias(context, NO);
    CGContextDrawImage(context, CGRectMake(0, 0, m_width, m_height), [image CGImage]);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    // now convert to grayscale
    uint8_t *m_imageData = (uint8_t *) malloc(m_width * m_height);
    for(int y = 0; y < m_height; y++) {
        for(int x = 0; x < m_width; x++) {
            uint32_t rgbPixel=rgbImage[y*m_width+x];
            uint32_t sum=0,count=0;
            if (colors & kRed) {sum += (rgbPixel>>24)&255; count++;}
            if (colors & kGreen) {sum += (rgbPixel>>16)&255; count++;}
            if (colors & kBlue) {sum += (rgbPixel>>8)&255; count++;}
            m_imageData[y*m_width+x]=sum/count;
        }
    }
    free(rgbImage);
    
    // convert from a gray scale image back into a UIImage
    uint8_t *result = (uint8_t *) calloc(m_width * m_height *sizeof(uint32_t), 1);
    
    // process the image back to rgb
    for(int i = 0; i < m_height * m_width; i++) {
        result[i*4]=0;
        int val=m_imageData[i];
        result[i*4+1]=val;
        result[i*4+2]=val;
        result[i*4+3]=val;
    }
    
    // create a UIImage
    colorSpace = CGColorSpaceCreateDeviceRGB();
    context = CGBitmapContextCreate(result, m_width, m_height, 8, m_width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGImageRef destImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIImage *resultUIImage = [UIImage imageWithCGImage:destImage];
    CGImageRelease(destImage);
    
    free(m_imageData);
    
    // make sure the data will be released by giving it to an autoreleased NSData
    [NSData dataWithBytesNoCopy:result length:m_width * m_height];
    
    return resultUIImage;
}


//이미지사이즈를 늘림 - 나인패치
#pragma resizableImageWithCapInsets
+ (UIImage*)resizableImageWithCapInsets:(UIEdgeInsets)make resizingMode:(UIImageResizingMode)resizingMode img:(UIImage *)img{
    UIImage *image = nil;
    if (IOS_VERSION < 6.0f) {
        image = [img resizableImageWithCapInsets:make];
    } else {
        image = [img resizableImageWithCapInsets:make resizingMode:resizingMode];
    }
    return image;
}

+ (UIImage *)stretchedImage:(UIImage *)srcImage expectSize:(CGSize)size {
    
    int st_width = size.width > srcImage.size.width ? (size.width - srcImage.size.width) / 2 : 0;
    int st_height = size.height > srcImage.size.height ? (size.height - srcImage.size.height) / 2 : 0;
    
    CGFloat capWidth = (st_width / 2);
    CGFloat capHeight = (st_height / 2);
    
    if (capWidth > 0) {
        capWidth = capWidth >= srcImage.size.width ? srcImage.size.width / 2 : capWidth;
    }
    
    if (capHeight > 0) {
        capHeight = capHeight >= srcImage.size.width ? srcImage.size.width / 2 : capHeight;
    }
    
    return [ImageUtil resizableImageWithCapInsets:UIEdgeInsetsMake(capHeight, capWidth, capHeight, capWidth) resizingMode:UIImageResizingModeStretch img:srcImage];
}


#pragma mark - Upload Util

- (void)prepareImagePicker {
    
    _alertController = [UIAlertController
                        alertControllerWithTitle:@"사진 선택"
                        message:nil
                        preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* album = [UIAlertAction actionWithTitle:@"사진앨범" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [_alertController dismissViewControllerAnimated:YES completion:nil];
        [self showImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
    }];
    
    UIAlertAction* camera = [UIAlertAction actionWithTitle:@"카메라" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [_alertController dismissViewControllerAnimated:YES completion:nil];
        [self showImagePickerController:UIImagePickerControllerSourceTypeCamera];
    }];
    
    
    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"취소" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [_alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [_alertController addAction:album];
    [_alertController addAction:camera];
    [_alertController addAction:cancel];
    
    UIViewController *vc = [CommonUtil currentViewController];
    [vc presentViewController:_alertController animated:YES completion:nil];
}


#pragma mark - 카메라/포토앨범 표시
- (void)showImagePickerController:(UIImagePickerControllerSourceType)sourceType
{
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    
    UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCancel.frame = CGRectMake(0, 0, 50, 30);
    [btnCancel setTitle:@"취소" forState:UIControlStateNormal];
    [btnCancel addTarget:self action:@selector(btnCancelTouched:) forControlEvents:UIControlEventTouchUpInside];
    
    _imagePickerController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnCancel];
    
    if ([UIImagePickerController isSourceTypeAvailable:sourceType]) {
        _imagePickerController.allowsEditing = YES;
        _imagePickerController.sourceType = sourceType;
        
        _imagePickerController.navigationBar.tintColor = [UIColor lightGrayColor]; //Cancel button text color
        _imagePickerController.navigationBar.translucent = NO;
        
        UIViewController *vc = [CommonUtil currentViewController];
        [vc presentViewController:_imagePickerController animated:YES completion:nil];
    }
}

- (void)btnCancelTouched:(id)sender {
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    CGRect cropRect = [[info valueForKey:UIImagePickerControllerCropRect] CGRectValue];
    //NSLog(@"cropRect: %@", NSStringFromCGRect(cropRect));
    
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    cropRect = [ImageUtil convertCropRect:cropRect image:image];
    image = [ImageUtil croppedImage:cropRect image:image];
    image = [ImageUtil resizeImage:image width:100.0f];
    
    UIViewController *vc = [CommonUtil currentViewController];
    [vc dismissViewControllerAnimated:YES completion:^{
        if ([self.delegate respondsToSelector:@selector(didFinishPickingImage:)]) {
            [self.delegate didFinishPickingImage:image];
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    UIViewController *vc = [CommonUtil currentViewController];
    [vc dismissViewControllerAnimated:YES completion:nil];
}

@end
