/*
 * 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+YSMultiFormat.h"
#import "YSSDImageCodersManager.h"

@implementation UIImage (YSMultiFormat)

+ (nullable UIImage *)yssd_imageWithData:(nullable NSData *)data {
    return [self yssd_imageWithData:data scale:1];
}

+ (nullable UIImage *)yssd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale {
    return [self yssd_imageWithData:data scale:scale firstFrameOnly:NO];
}

+ (nullable UIImage *)yssd_imageWithData:(nullable NSData *)data scale:(CGFloat)scale firstFrameOnly:(BOOL)firstFrameOnly {
    if (!data) {
        return nil;
    }
    YSSDImageCoderOptions *options = @{YSSDImageCoderDecodeScaleFactor : @(MAX(scale, 1)), YSSDImageCoderDecodeFirstFrameOnly : @(firstFrameOnly)};
    return [[YSSDImageCodersManager sharedManager] decodedImageWithData:data options:options];
}

- (nullable NSData *)yssd_imageData {
    return [self yssd_imageDataAsFormat:YSSDImageFormatUndefined];
}

- (nullable NSData *)yssd_imageDataAsFormat:(YSSDImageFormat)imageFormat {
    return [self yssd_imageDataAsFormat:imageFormat compressionQuality:1];
}

- (nullable NSData *)yssd_imageDataAsFormat:(YSSDImageFormat)imageFormat compressionQuality:(double)compressionQuality {
    return [self yssd_imageDataAsFormat:imageFormat compressionQuality:compressionQuality firstFrameOnly:NO];
}

- (nullable NSData *)yssd_imageDataAsFormat:(YSSDImageFormat)imageFormat compressionQuality:(double)compressionQuality firstFrameOnly:(BOOL)firstFrameOnly {
    YSSDImageCoderOptions *options = @{YSSDImageCoderEncodeCompressionQuality : @(compressionQuality), YSSDImageCoderEncodeFirstFrameOnly : @(firstFrameOnly)};
    return [[YSSDImageCodersManager sharedManager] encodedDataWithImage:self format:imageFormat options:options];
}

@end
