//
//  KBWebImageManager.m
//  keyBoard
//

#import "KBWebImageManager.h"
#import <SDWebImage/SDWebImage.h>

static inline NSURL *_KBURL(id url) {
    if (!url) return nil;
    if ([url isKindOfClass:NSURL.class]) return url;
    if ([url isKindOfClass:NSString.class]) return [NSURL URLWithString:(NSString *)url];
    return nil;
}

@implementation KBWebImageManager

+ (void)prefetchURLs:(NSArray<id> *)urlList
            progress:(void(^)(NSUInteger finished, NSUInteger total))progress
           completed:(void(^)(NSUInteger finished, NSUInteger skipped))completed {
    NSMutableArray<NSURL *> *urls = [NSMutableArray arrayWithCapacity:urlList.count];
    for (id u in urlList) { NSURL *nu = _KBURL(u); if (nu) [urls addObject:nu]; }
    [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:urls progress:^(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls) {
        if (progress) progress(noOfFinishedUrls, noOfTotalUrls);
    } completed:^(NSUInteger finishedCount, NSUInteger skippedCount) {
        if (completed) completed(finishedCount, skippedCount);
    }];
}

+ (void)calculateDiskSize:(void(^)(NSUInteger bytes))completion {
    [[SDImageCache sharedImageCache] calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
        if (completion) completion(totalSize);
    }];
}

+ (void)clearAllCache:(void(^)(void))completion {
    SDImageCache *cache = SDImageCache.sharedImageCache;
    [cache clearMemory];
    [cache clearDiskOnCompletion:^{ if (completion) completion(); }];
}

+ (void)setHTTPHeaderValue:(NSString *)value forKey:(NSString *)field {
    if (value.length == 0) {
        [[SDWebImageDownloader sharedDownloader] setValue:nil forHTTPHeaderField:field];
    } else {
        [[SDWebImageDownloader sharedDownloader] setValue:value forHTTPHeaderField:field];
    }
}

@end

