//
//  NSObject+ZYJMJCoding.m
//  ZYJMJExtension
//
//  Created by mj on 14-1-15.
//  Copyright (c) 2014年 小码哥. All rights reserved.
//

#import "NSObject+ZYJMJCoding.h"
#import "NSObject+ZYJMJClass.h"
#import "NSObject+ZYJMJProperty.h"
#import "ZYJMJProperty.h"

@implementation NSObject (ZYJMJCoding)

- (void)mj_ZYJencode:(NSCoder *)encoder
{
    Class clazz = [self class];
    
    NSArray *allowedCodingPropertyNames = [clazz mj_ZYJtotalAllowedCodingPropertyNames];
    NSArray *ignoredCodingPropertyNames = [clazz mj_ZYJtotalIgnoredCodingPropertyNames];
    
    [clazz mj_ZYJenumerateProperties:^(ZYJMJProperty *property, BOOL *stop) {
        // 检测是否被忽略
        if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
        if ([ignoredCodingPropertyNames containsObject:property.name]) return;
        
        id value = [property valueForObject:self];
        if (value == nil) return;
        [encoder encodeObject:value forKey:property.name];
    }];
}

- (void)mj_ZYJdecode:(NSCoder *)decoder
{
    Class clazz = [self class];
    
    NSArray *allowedCodingPropertyNames = [clazz mj_ZYJtotalAllowedCodingPropertyNames];
    NSArray *ignoredCodingPropertyNames = [clazz mj_ZYJtotalIgnoredCodingPropertyNames];
    
    [clazz mj_ZYJenumerateProperties:^(ZYJMJProperty *property, BOOL *stop) {
        // 检测是否被忽略
        if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
        if ([ignoredCodingPropertyNames containsObject:property.name]) return;
        
        id value = [decoder decodeObjectForKey:property.name];
        if (value == nil) { // 兼容以前的ZYJMJExtension版本
            value = [decoder decodeObjectForKey:[@"_" stringByAppendingString:property.name]];
        }
        if (value == nil) return;
        [property setValue:value forObject:self];
    }];
}
@end
