//
// Created by Yaotian on 2/7/14.
// Copyright (c) 2014 Kollway Mobile. All rights reserved.
//

#import "KWMImageUtil.h"
#import "KWMStringUtil.h"
#import "Buy/Buy.h"
#import <RegexKitLite/RegexKitLite.h>


@implementation KWMImageUtil {
    
}

+ (UIImage *)createTransparentImage {
    UIImage *result = nil;
    
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}


+ (UIImage *)createColorImage:(UIColor *)color pixelSize:(CGSize)size {
    UIImage *result = nil;
    
    CGRect rect = CGRectMake(0, 0, 0, 0);
    rect.size = size;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    [color setFill];
    UIRectFill(rect); // Fill it with your color
    result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return result;
}

+ (UIImage *)createColorImage:(UIColor *)color {
    return [self createColorImage:color pixelSize:CGSizeMake(1, 1)];
}

+ (UIImage *)createGradientImage:(UIColor *)startColor endColor:(UIColor *)endColor size:(CGSize)size {
    UIImage *result = nil;
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    
    CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
    
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat r0;
    CGFloat g0;
    CGFloat b0;
    CGFloat a0;
    CGFloat r1;
    CGFloat g1;
    CGFloat b1;
    CGFloat a1;
    [startColor getRed:&r0 green:&g0 blue:&b0 alpha:&a0];
    [endColor getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
    CGFloat components[8] = {
        r0, g0, b0, a0,   // Start color
        r1, g1, b1, a1 }; // End color
    CGGradientRef gradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    CGContextDrawLinearGradient(currentContext, gradient, CGPointMake(0, 0), CGPointMake(0, size.height), 0);
    
    result = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGColorSpaceRelease(rgbColorspace);
    
    return result;
}

// 计算文件大小,单位KB
+ (float)fileSizeAtPath:(NSString*)filePath{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1024.0;
    }
    return 0;
}

+ (BOOL)saveJPGImageToFile:(NSString *)filePath image:(UIImage *)image {
    NSData *data = UIImageJPEGRepresentation(image, .8f);
    return [data writeToFile:filePath atomically:YES];
}

+ (BOOL)savePNGImageToFile:(NSString *)filePath image:(UIImage *)image {
    NSData *data = UIImagePNGRepresentation(image);
    return [data writeToFile:filePath atomically:YES];
}

+ (UIImage *)getImageFromFile:(NSString *)filePath {
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    return [UIImage imageWithData:data];
}

+ (void)deleteLocalImage:(NSString *)imagePath {
    if (imagePath == nil || imagePath.length <= 0) {
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:imagePath]) {
        NSError *error;
        [fileManager removeItemAtPath:imagePath error:&error];
    }
}

+ (UIImage *)imageWithImage:(UIImage *)image scaledToPixelSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)imageAfterZoom:(UIImage *)image scale:(float)scale {
    float newWidth = image.size.width * scale;
    float newHeight = image.size.height * scale;
    CGSizeMake(newWidth, newHeight);
    return [self imageWithImage:image scaledToPixelSize:CGSizeMake(newWidth, newHeight)];
}

+(NSArray *)getOriginalImages1:(BUYProduct *)product{
    NSMutableArray *productImages = [[NSMutableArray alloc]init];
    if(!product){
        return productImages;
    }
    NSArray *imageLinks = product.imagesArray;
    if(!imageLinks || imageLinks.count == 0){
        return productImages;
    }
    for(BUYImageLink *imageLink in imageLinks){
        NSString *productImage = imageLink.sourceURL.absoluteString;
        [productImages addObject:productImage];
    }
    return productImages;
}


+(NSArray *)getOriginalImages2:(KWMDataProduct *)product{
    NSMutableArray *productImages = [[NSMutableArray alloc]init];
    if(!product){
        return productImages;
    }
    NSArray *imageLinks = product.images;
    if(!imageLinks || imageLinks.count == 0){
        return productImages;
    }
    for(NSDictionary *imageLink in imageLinks){
        if(imageLink[@"src"]){
            NSString *originalImage = imageLink[@"src"];
            [productImages addObject:originalImage];
        }
    }
    return productImages;
}


+(NSArray *)getImageArrayBySize:(id)product ImageSize:(NSInteger)ImageSize{
    NSArray *imageArray = nil;
    if([product isKindOfClass:[BUYProduct class]]){
        imageArray = [self getOriginalImages1:product];
    }
    if([product isKindOfClass:[KWMDataProduct class]]){
        imageArray = [self getOriginalImages2:product];
    }
    NSMutableArray *newImageArray = [[NSMutableArray alloc]init];
    if(imageArray && imageArray.count>0){
        for(NSString *imageUrl in imageArray){
            NSString *newImageUrl = [self getProductImageUrlByOriginalUrl:imageUrl ImageSize:ImageSize];
            [newImageArray addObject:newImageUrl];
        }
    }
    return newImageArray;
}


+ (NSString *)getProductImageUrlByOriginalUrl:(NSString *)originalImgUrl ImageSize:(NSInteger)ImageSize{
    NSMutableString *newImageUrl = [[NSMutableString alloc]initWithString:[originalImgUrl stringByReplacingOccurrencesOfString:@"?" withString:@"%3F"]];;
    //https://cdn.shopify.com/s/files/1/1089/5284/products/5413_1.jpg?v==1459708223 转换为
    //https://o42yton8r.qnssl.com/s/files/1/1089/5284/products/5413_1.jpg?imageView2/1/w/300/h/300/v==1459708223
//    if(originalImgUrl){
//        NSRange startRange = [originalImgUrl rangeOfString:@"?"];
//        if (startRange.location != NSNotFound) {
//            newImageUrl=[[NSMutableString alloc]initWithString:originalImgUrl];
//            NSArray<NSString *> *imageWH = [self getImageWH:ImageSize];
//            NSString *size = [NSString stringWithFormat:@"imageView2/2/w/%@/h/%@/",imageWH[0],imageWH[1]];
//            [newImageUrl insertString:size atIndex:startRange.location+1];
//        }
//    }
    NSArray<NSString *> *imageWH = [self getImageWH:ImageSize];
    NSString *size = [NSString stringWithFormat:@"?imageView2/2/w/%@/h/%@/",imageWH[0],imageWH[1]];
    [newImageUrl appendString:size];
    
    return [newImageUrl stringByReplacingOccurrencesOfString:@"cdn.shopify.com" withString:Image_Domain];

}

+(NSArray *)getImageWH:(NSInteger)ImageSize{
    switch (ImageSize) {
        case BigImage:
            return @[@"1000", @"1000"];
        case SmallImage:
            return @[@"300", @"300"];
        case LowImage:
            return @[@"150", @"150"];
        case NormalImage:
            return @[@"500", @"500"];
        default:
            return @[@"300", @"300"];
    }
}

+ (NSArray *)getProductImageUrls:(id)product ImageSize:(NSInteger)ImageSize{
    NSArray *imageUrls = nil;
    if(product){
        imageUrls = [self getImageArrayBySize:product ImageSize:ImageSize];
        return imageUrls;
    }
    return nil;
}

+ (NSString *)getProductImageUrl:(id)product ImageSize:(NSInteger)ImageSize{
    NSString *imageUrl = @"";
    if(product){
        NSArray *imageArray = [self getImageArrayBySize:product ImageSize:ImageSize];
        if(imageArray && imageArray.count>0){
            imageUrl = imageArray.firstObject;
        }
    }
    return imageUrl;
}


+ (NSString *)getProductImageUrlByPosition:(id)product ImageSize:(NSInteger)ImageSize Position:(NSInteger)Position{
    NSString *imageUrl = @"";
    if(product){
        NSArray *imageArray = [self getImageArrayBySize:product ImageSize:ImageSize];
        if(imageArray && imageArray.count>Position){
            return imageArray[Position];
        }
    }
    return imageUrl;
}





@end