/*
* 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 "YSSDWebImageDownloaderDecryptor.h"

@interface YSSDWebImageDownloaderDecryptor ()

@property (nonatomic, copy, nonnull) YSSDWebImageDownloaderDecryptorBlock block;

@end

@implementation YSSDWebImageDownloaderDecryptor

- (instancetype)initWithBlock:(YSSDWebImageDownloaderDecryptorBlock)block {
    self = [super init];
    if (self) {
        self.block = block;
    }
    return self;
}

+ (instancetype)decryptorWithBlock:(YSSDWebImageDownloaderDecryptorBlock)block {
    YSSDWebImageDownloaderDecryptor *decryptor = [[YSSDWebImageDownloaderDecryptor alloc] initWithBlock:block];
    return decryptor;
}

- (nullable NSData *)decryptedDataWithData:(nonnull NSData *)data response:(nullable NSURLResponse *)response {
    if (!self.block) {
        return nil;
    }
    return self.block(data, response);
}

@end

@implementation YSSDWebImageDownloaderDecryptor (Conveniences)

+ (YSSDWebImageDownloaderDecryptor *)base64Decryptor {
    static YSSDWebImageDownloaderDecryptor *decryptor;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        decryptor = [YSSDWebImageDownloaderDecryptor decryptorWithBlock:^NSData * _Nullable(NSData * _Nonnull data, NSURLResponse * _Nullable response) {
            NSData *modifiedData = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters];
            return modifiedData;
        }];
    });
    return decryptor;
}

@end
