#import "TQWarmupManifest.h"

@implementation TQWarmupBizType
@end

@implementation TQWarmupManifest

+ (nullable TQWarmupManifest *)parse:(NSData *)data {
    if (data == nil) {
        return nil;
    }
    NSError *err = nil;
    id root = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    if (err != nil || ![root isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSDictionary *dict = (NSDictionary *)root;
    id hostsObj = dict[@"hosts"];
    if (![hostsObj isKindOfClass:[NSArray class]]) {
        return nil;
    }
    TQWarmupManifest *m = [[TQWarmupManifest alloc] init];
    m.version = [dict[@"version"] isKindOfClass:[NSString class]] ? dict[@"version"] : @"";
    m.hosts = (NSArray *)hostsObj;

    NSMutableDictionary<NSString *, TQWarmupBizType *> *bizTypes = [NSMutableDictionary dictionary];
    id bizObj = dict[@"bizTypes"];
    if ([bizObj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *bizDict = (NSDictionary *)bizObj;
        for (NSString *key in bizDict) {
            id biz = bizDict[key];
            if (![biz isKindOfClass:[NSDictionary class]]) {
                continue;
            }
            TQWarmupBizType *bt = [[TQWarmupBizType alloc] init];
            bt.warmupUrl = [biz[@"warmupUrl"] isKindOfClass:[NSString class]] ? biz[@"warmupUrl"] : @"";
            id assets = biz[@"assets"];
            bt.assets = [assets isKindOfClass:[NSArray class]] ? assets : @[];
            bizTypes[key] = bt;
        }
    }
    m.bizTypes = bizTypes;
    id menuArr = dict[@"menuBizTypes"];
    if ([menuArr isKindOfClass:[NSArray class]]) {
        m.menuBizTypes = (NSArray *)menuArr;
    }
    return m;
}

@end
