#import "NSObject+XXGModel.h"
#import <objc/runtime.h>

@implementation NSObject (XXGModel)

+ (instancetype)xxpk_modelWithDict:(NSDictionary *)dict {
    if (![dict isKindOfClass:[NSDictionary class]]) return nil;
    
    id model = [[self alloc] init];
    
    
    NSArray *propertyNames = [self xxpk_propertyNames];
    NSDictionary *keyMapping = [self xxpk_replacedKeyFromPropertyName];
    NSDictionary *arrayMapping = [self xxpk_objectClassInArray];
    
    for (NSString *propertyName in propertyNames) {
        
        NSString *keyPath = keyMapping[propertyName] ?: propertyName;
        
        
        id value = [dict valueForKeyPath:keyPath];

        if (!value || [value isKindOfClass:[NSNull class]]) continue;
        
        
        NSString *propertyType = [self xxpk_propertyTypeForPropertyName:propertyName];
        
        
        value = [self xxpk_convertValue:value
                       forPropertyName:propertyName
                              keyPath:keyPath
                        propertyType:propertyType
                       arrayMapping:arrayMapping
                              parentDict:dict];
        
        
        if (value) {
            @try {
                [model setValue:value forKey:propertyName];
            } @catch (NSException *exception) {

            }
        }
    }
    return model;
}

+ (NSArray *)xxpk_modelArrayWithDictArray:(NSArray *)dictArray {
    
    if (![dictArray isKindOfClass:[NSArray class]]) return @[];
    
    
    NSMutableArray *modelArray = [NSMutableArray arrayWithCapacity:dictArray.count];
    
    
    for (id element in dictArray) {
        
        if (![element isKindOfClass:[NSDictionary class]]) {

            continue;
        }
        
        
        id model = [self xxpk_modelWithDict:element];
        
        
        if (model) {
            [modelArray addObject:model];
        }
    }
    
    return [modelArray copy];
}

- (NSMutableDictionary *)xxpk_modelToDict {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    
    NSArray *propertyNames = [[self class] xxpk_propertyNames];
    NSDictionary *keyMapping = [[self class] xxpk_replacedKeyFromPropertyName];
    NSDictionary *arrayMapping = [[self class] xxpk_objectClassInArray];
    
    for (NSString *propertyName in propertyNames) {
        NSString *keyPath = keyMapping[propertyName] ?: propertyName;
        id value = [self valueForKey:propertyName];
        
        if (!value || [value isKindOfClass:[NSNull class]]) continue;
        
        
        if ([value isKindOfClass:[NSObject class]] &&
            ![value isKindOfClass:[NSString class]] &&
            ![value isKindOfClass:[NSNumber class]] &&
            ![value isKindOfClass:[NSArray class]] &&
            ![value isKindOfClass:[NSDictionary class]]) {
            
            value = [value xxpk_modelToDict];
        }
        
        
        if ([value isKindOfClass:[NSArray class]]) {
            NSMutableArray *convertedArray = [NSMutableArray array];
            
            
            Class elementClass = arrayMapping[propertyName];
            if (!elementClass) {
                
                NSString *className = [[self class] xxpk_objectClassInArray][propertyName];
                elementClass = NSClassFromString(className);
            }
            
            for (id item in value) {
                if (elementClass && [item isKindOfClass:elementClass]) {
                    
                    [convertedArray addObject:[item xxpk_modelToDict]];
                } else if ([item isKindOfClass:[NSObject class]] &&
                          ![item isKindOfClass:[NSString class]] &&
                          ![item isKindOfClass:[NSNumber class]]) {
                    
                    [convertedArray addObject:[item xxpk_modelToDict]];
                } else {
                    [convertedArray addObject:item];
                }
            }
            value = [convertedArray copy];
        }
        
        
        if ([keyPath containsString:@"."]) {
            NSArray *keys = [keyPath componentsSeparatedByString:@"."];
            __block NSMutableDictionary *currentDict = dict;
            
            [keys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
                if (idx == keys.count - 1) {
                    currentDict[key] = value;
                } else {
                    if (!currentDict[key] || ![currentDict[key] isKindOfClass:[NSMutableDictionary class]]) {
                        currentDict[key] = [NSMutableDictionary dictionary];
                    }
                    currentDict = currentDict[key];
                }
            }];
        } else {
            dict[keyPath] = value;
        }
    }
    
    return [dict mutableCopy];
}



+ (NSArray<NSString *> *)xxpk_propertyNames {
    NSMutableArray *names = [NSMutableArray array];
    Class cls = self;
    
    
    while (cls != [NSObject class]) {
        unsigned int count;
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        
        for (unsigned int i = 0; i < count; i++) {
            objc_property_t property = properties[i];
            const char *name = property_getName(property);
            NSString *propertyName = [NSString stringWithUTF8String:name];
            
            
            if (![names containsObject:propertyName]) {
                [names addObject:propertyName];
            }
        }
        free(properties);
        
        
        cls = [cls superclass];
    }
    return [names copy];
}


+ (id)xxpk_convertValue:(id)value
       forPropertyName:(NSString *)propertyName
              keyPath:(NSString *)keyPath
        propertyType:(NSString *)propertyType
       arrayMapping:(NSDictionary *)arrayMapping
        parentDict:(NSDictionary *)parentDict {
    
    
    if ([value isKindOfClass:[NSDictionary class]]) {
        
        Class modelClass = NSClassFromString(propertyType);

        
        
        BOOL isValidClass = modelClass &&
                           ![modelClass isSubclassOfClass:[NSDictionary class]] &&
                           ![modelClass isSubclassOfClass:[NSArray class]] &&
                           [modelClass respondsToSelector:@selector(xxpk_modelWithDict:)];
        
        if (!isValidClass) {

            return value; 
        }
        
        

        id convertedModel = [modelClass xxpk_modelWithDict:value];
        
        
        if (!convertedModel) {

        }
        return convertedModel;
    }
    
    
    if ([value isKindOfClass:[NSArray class]]) {
        Class itemClass = NSClassFromString(arrayMapping[propertyName]);
        if (itemClass) {
            NSMutableArray *models = [NSMutableArray array];
            for (id subValue in value) {
                if ([subValue isKindOfClass:[NSDictionary class]]) {
                    [models addObject:[itemClass xxpk_modelWithDict:subValue]];
                } else {
                    [models addObject:subValue];
                }
            }
            return models;
        }
    }
    
    
    if ([keyPath containsString:@"."] && [value isKindOfClass:[NSString class]]) {
        return [self xxpk_convertBasicTypeValue:value propertyType:propertyType];
    }
    
    return [self xxpk_convertBasicTypeValue:value propertyType:propertyType];
}


+ (id)xxpk_convertBasicTypeValue:(id)value propertyType:(NSString *)type {
    if ([value isKindOfClass:[NSString class]]) {
        NSString *stringValue = (NSString *)value;
        
        if ([type isEqualToString:@"NSString"]) {
            return stringValue;
        }
        if ([type isEqualToString:@"BOOL"]) {
            return @([stringValue boolValue] ||
                    [stringValue.lowercaseString isEqualToString:@"yes"] ||
                    [stringValue.lowercaseString isEqualToString:@"true"]);
        }
        if ([type isEqualToString:@"NSInteger"]) {
            return @([stringValue integerValue]);
        }
        if ([type isEqualToString:@"int"]) {
            return @([stringValue intValue]);
        }
        if ([type isEqualToString:@"double"]) {
            return @([stringValue doubleValue]);
        }
        if ([type isEqualToString:@"float"]) {
            return @([stringValue floatValue]);
        }
        if ([type isEqualToString:@"NSNumber"]) {
            return [[NSNumberFormatter new] numberFromString:stringValue] ?: @0;
        }
    }
    
    
    if ([value isKindOfClass:[NSNumber class]]) {
        if ([type isEqualToString:@"NSString"]) {
            return [value stringValue];
        }
    }
    
    return value;
}


+ (NSString *)xxpk_propertyTypeForPropertyName:(NSString *)name {
    objc_property_t property = class_getProperty(self, name.UTF8String);
    if (!property) return nil;
    
    const char *attrs = property_getAttributes(property);
    NSString *attributeStr = [NSString stringWithUTF8String:attrs];
    
    
    if ([attributeStr containsString:@"@\""]) {
        NSRange range = [attributeStr rangeOfString:@"@\""];
        NSString *typeStr = [attributeStr substringFromIndex:range.location+2];
        typeStr = [typeStr componentsSeparatedByString:@"\""].firstObject;
        return typeStr;
    }
    
    
    const char typeCode = attrs[1];
    switch (typeCode) {
        case 'B': return @"BOOL";
        case 'q': return @"NSInteger";
        case 'i': return @"int";
        case 'd': return @"double";
        case 'f': return @"float";
        default: return nil;
    }
}


+ (NSDictionary *)xxpk_replacedKeyFromPropertyName {
    return @{};
}


+ (NSDictionary *)xxpk_objectClassInArray {
    return @{};
}


- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

@end
