//
//  GMTabBarIconManager.m
//  Gengmei
//
//  Created by 汪俊 on 2016/12/21.
//  Copyright © 2016年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMTabBarIconManager.h"
#import "GMLaunchManager.h"

#define kTabbarConfigKey @"kTabbarConfigKey"
#import <SDWebImage/SDWebImagePrefetcher.h>

@implementation GMTabBarIconManager
/**
 获取存储的tabbarIcons数据
 */
+ (NSArray<GMTabIconConfigObject> *)tabbarConfig
{
    return [GMCache fetchObjectAtDiskWithkey:kTabbarConfigKey];
}

/**
 服务器会返回五个位置的tab,如果不配置返回空字符串占位
 */
+ (void)downloadTabbarIcons {
    [self.tabbarConfig enumerateObjectsUsingBlock:^(GMTabIconConfigObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self tabbarIconsIsExistWithKey:obj.iconNormal] && [obj.iconNormal isNonEmpty]) {
            //下载normal图片
            [self downloadTabIconWithUrl:obj.iconNormal];
        }
        if (![self tabbarIconsIsExistWithKey:obj.iconPressed] && [obj.iconPressed isNonEmpty]) {
            //下载pressed图片
            [self downloadTabIconWithUrl:obj.iconPressed];
        }
    }];
}

///根据存取的key判断需要下载的图片是否已经本地缓存过(key为空时,把本地的tabBar Icon当做缓存的icon)
+ (BOOL)tabbarIconsIsExistWithKey:(NSString *)key {
    if ([[SDImageCache sharedImageCache] diskImageExistsWithKey:key] || ![key isNonEmpty]) {
        return YES;
    } else {
        return NO;
    }
}

//判断本地是否有下载完整的tabBarIcon,有一个没下载好都不去替换
+ (BOOL)hasTotalTabbarIconsFromDisk {
    NSArray<GMTabIconConfigObject *> *tabbarIcons = self.tabbarConfig;
    BOOL isTotal = NO;
    for (NSInteger i = 0; i < tabbarIcons.count; i++) {
        if ([self tabbarIconsIsExistWithKey:tabbarIcons[i].iconPressed] && [self tabbarIconsIsExistWithKey:tabbarIcons[i].iconNormal]) {
            isTotal = YES;
            continue;
        } else {
            isTotal = NO;
            break;
        }
    }
    return isTotal;
    
}

/// 根据url下载去下载tabBar的图片
+ (void)downloadTabIconWithUrl:(NSString *)url {
    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    }];
}

/// 取出本地已经下载好的tabBar的图片
+ (NSMutableArray *)localTabBarIcons {
    NSMutableArray *icons= [NSMutableArray array];
    [self.tabbarConfig enumerateObjectsUsingBlock:^(GMTabIconConfigObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.normalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:obj.iconNormal];
        obj.pressedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:obj.iconPressed];
        [icons addObject:obj];
    }];
    return icons;
}

+ (void)saveTabbarConfig {
    [GMCache storeObjectAtDiskWithkey:kTabbarConfigKey object:[GMLaunchManager shareManager].appConfigObject.tabs];
}

@end
