/*
 * This file is part of the YSSDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "YSSDWebImageDefine.h"
#import "UIImage+YSMetadata.h"
#import "NSImage+YSCompatibility.h"
#import "YSSDAssociatedObject.h"

#pragma mark - Image scale

static inline NSArray<NSNumber *> * _Nonnull YSSDImageScaleFactors() {
    return @[@2, @3];
}

inline CGFloat YSSDImageScaleFactorForKey(NSString * _Nullable key) {
    CGFloat scale = 1;
    if (!key) {
        return scale;
    }
    // Check if target OS support scale
#if YSSD_WATCH
    if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)])
#elif YSSD_UIKIT
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
#elif YSSD_MAC
    if ([[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)])
#endif
    {
        // a@2x.png -> 8
        if (key.length >= 8) {
            // Fast check
            BOOL isURL = [key hasPrefix:@"http://"] || [key hasPrefix:@"https://"];
            for (NSNumber *scaleFactor in YSSDImageScaleFactors()) {
                // @2x. for file name and normal url
                NSString *fileScale = [NSString stringWithFormat:@"@%@x.", scaleFactor];
                if ([key containsString:fileScale]) {
                    scale = scaleFactor.doubleValue;
                    return scale;
                }
                if (isURL) {
                    // %402x. for url encode
                    NSString *urlScale = [NSString stringWithFormat:@"%%40%@x.", scaleFactor];
                    if ([key containsString:urlScale]) {
                        scale = scaleFactor.doubleValue;
                        return scale;
                    }
                }
            }
        }
    }
    return scale;
}

inline UIImage * _Nullable YSSDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) {
    if (!image) {
        return nil;
    }
    CGFloat scale = YSSDImageScaleFactorForKey(key);
    return YSSDScaledImageForScaleFactor(scale, image);
}

inline UIImage * _Nullable YSSDScaledImageForScaleFactor(CGFloat scale, UIImage * _Nullable image) {
    if (!image) {
        return nil;
    }
    if (scale <= 1) {
        return image;
    }
    if (scale == image.scale) {
        return image;
    }
    UIImage *scaledImage;
    if (image.yssd_isAnimated) {
        UIImage *animatedImage;
#if YSSD_UIKIT || YSSD_WATCH
        // `UIAnimatedImage` images share the same size and scale.
        NSMutableArray<UIImage *> *scaledImages = [NSMutableArray array];
        
        for (UIImage *tempImage in image.images) {
            UIImage *tempScaledImage = [[UIImage alloc] initWithCGImage:tempImage.CGImage scale:scale orientation:tempImage.imageOrientation];
            [scaledImages addObject:tempScaledImage];
        }
        
        animatedImage = [UIImage animatedImageWithImages:scaledImages duration:image.duration];
        animatedImage.yssd_imageLoopCount = image.yssd_imageLoopCount;
#else
        // Animated GIF for `NSImage` need to grab `NSBitmapImageRep`;
        NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height);
        NSImageRep *imageRep = [image bestRepresentationForRect:imageRect context:nil hints:nil];
        NSBitmapImageRep *bitmapImageRep;
        if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) {
            bitmapImageRep = (NSBitmapImageRep *)imageRep;
        }
        if (bitmapImageRep) {
            NSSize size = NSMakeSize(image.size.width / scale, image.size.height / scale);
            animatedImage = [[NSImage alloc] initWithSize:size];
            bitmapImageRep.size = size;
            [animatedImage addRepresentation:bitmapImageRep];
        }
#endif
        scaledImage = animatedImage;
    } else {
#if YSSD_UIKIT || YSSD_WATCH
        scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
#else
        scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:kCGImagePropertyOrientationUp];
#endif
    }
    YSSDImageCopyAssociatedObject(image, scaledImage);
    
    return scaledImage;
}

#pragma mark - Context option

YSSDWebImageContextOption const YSSDWebImageContextSetImageOperationKey = @"setImageOperationKey";
YSSDWebImageContextOption const YSSDWebImageContextCustomManager = @"customManager";
YSSDWebImageContextOption const YSSDWebImageContextImageCache = @"imageCache";
YSSDWebImageContextOption const YSSDWebImageContextImageLoader = @"imageLoader";
YSSDWebImageContextOption const YSSDWebImageContextImageCoder = @"imageCoder";
YSSDWebImageContextOption const YSSDWebImageContextImageTransformer = @"imageTransformer";
YSSDWebImageContextOption const YSSDWebImageContextImageScaleFactor = @"imageScaleFactor";
YSSDWebImageContextOption const YSSDWebImageContextImagePreserveAspectRatio = @"imagePreserveAspectRatio";
YSSDWebImageContextOption const YSSDWebImageContextImageThumbnailPixelSize = @"imageThumbnailPixelSize";
YSSDWebImageContextOption const YSSDWebImageContextQueryCacheType = @"queryCacheType";
YSSDWebImageContextOption const YSSDWebImageContextStoreCacheType = @"storeCacheType";
YSSDWebImageContextOption const YSSDWebImageContextOriginalQueryCacheType = @"originalQueryCacheType";
YSSDWebImageContextOption const YSSDWebImageContextOriginalStoreCacheType = @"originalStoreCacheType";
YSSDWebImageContextOption const YSSDWebImageContextAnimatedImageClass = @"animatedImageClass";
YSSDWebImageContextOption const YSSDWebImageContextDownloadRequestModifier = @"downloadRequestModifier";
YSSDWebImageContextOption const YSSDWebImageContextDownloadResponseModifier = @"downloadResponseModifier";
YSSDWebImageContextOption const YSSDWebImageContextDownloadDecryptor = @"downloadDecryptor";
YSSDWebImageContextOption const YSSDWebImageContextCacheKeyFilter = @"cacheKeyFilter";
YSSDWebImageContextOption const YSSDWebImageContextCacheSerializer = @"cacheSerializer";
