/*
 * 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 "UIImage+YSMemoryCacheCost.h"
#import "objc/runtime.h"
#import "NSImage+YSCompatibility.h"

FOUNDATION_STATIC_INLINE NSUInteger YSSDMemoryCacheCostForImage(UIImage *image) {
    CGImageRef imageRef = image.CGImage;
    if (!imageRef) {
        return 0;
    }
    NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef);
    NSUInteger frameCount;
#if YSSD_MAC
    frameCount = 1;
#elif YSSD_UIKIT || YSSD_WATCH
    frameCount = image.images.count > 0 ? image.images.count : 1;
#endif
    NSUInteger cost = bytesPerFrame * frameCount;
    return cost;
}

@implementation UIImage (YSMemoryCacheCost)

- (NSUInteger)yssd_memoryCost {
    NSNumber *value = objc_getAssociatedObject(self, @selector(yssd_memoryCost));
    NSUInteger memoryCost;
    if (value != nil) {
        memoryCost = [value unsignedIntegerValue];
    } else {
        memoryCost = YSSDMemoryCacheCostForImage(self);
    }
    return memoryCost;
}

- (void)setYssd_memoryCost:(NSUInteger)yssd_memoryCost {
    objc_setAssociatedObject(self, @selector(yssd_memoryCost), @(yssd_memoryCost), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
