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

#import "ZYJMJPropertyType.h"
#import "ZYJMJExtension.h"
#import "ZYJMJFoundation.h"
#import "ZYJMJExtensionConst.h"

@implementation ZYJMJPropertyType

static NSMutableDictionary *types_;
+ (void)initialize
{
    types_ = [NSMutableDictionary dictionary];
}

+ (instancetype)cachedTypeWithCode:(NSString *)code
{
    ZYJMJExtensionAssertParamNotNil2(code, nil);
    @synchronized (self) {
        ZYJMJPropertyType *type = types_[code];
        if (type == nil) {
            type = [[self alloc] init];
            type.code = code;
            types_[code] = type;
        }
        return type;
    }
}

#pragma mark - 公共方法
- (void)setCode:(NSString *)code
{
    _code = code;
    
    ZYJMJExtensionAssertParamNotNil(code);
    
    if ([code isEqualToString:ZYJMJPropertyTypeId]) {
        _idType = YES;
    } else if (code.length == 0) {
        _KVCDisabled = YES;
    } else if (code.length > 3 && [code hasPrefix:@"@\""]) {
        // 去掉@"和"，截取中间的类型名称
        _code = [code substringWithRange:NSMakeRange(2, code.length - 3)];
        _typeClass = NSClassFromString(_code);
        _fromFoundation = [ZYJMJFoundation isClassFromFoundation:_typeClass];
        _numberType = [_typeClass isSubclassOfClass:[NSNumber class]];
        
    } else if ([code isEqualToString:ZYJMJPropertyTypeSEL] ||
               [code isEqualToString:ZYJMJPropertyTypeIvar] ||
               [code isEqualToString:ZYJMJPropertyTypeMethod]) {
        _KVCDisabled = YES;
    }
    
    // 是否为数字类型
    NSString *lowerCode = _code.lowercaseString;
    NSArray *numberTypes = @[ZYJMJPropertyTypeInt, ZYJMJPropertyTypeShort, ZYJMJPropertyTypeBOOL1, ZYJMJPropertyTypeBOOL2, ZYJMJPropertyTypeFloat, ZYJMJPropertyTypeDouble, ZYJMJPropertyTypeLong, ZYJMJPropertyTypeLongLong, ZYJMJPropertyTypeChar];
    if ([numberTypes containsObject:lowerCode]) {
        _numberType = YES;
        
        if ([lowerCode isEqualToString:ZYJMJPropertyTypeBOOL1]
            || [lowerCode isEqualToString:ZYJMJPropertyTypeBOOL2]) {
            _boolType = YES;
        }
    }
}
@end
