//
//  BaseClass.m
//
//  Created by  黄 on 2017/1/23
//  Copyright (c) 2017 __MyCompanyName__. All rights reserved.
//

#import "BaseClass.h"
#import "Result.h"


NSString *const kBaseClassResult = @"result";
NSString *const kBaseClassErrorCode = @"error_code";
NSString *const kBaseClassReason = @"reason";


@interface BaseClass ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation BaseClass

@synthesize result = _result;
@synthesize errorCode = _errorCode;
@synthesize reason = _reason;


+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict {
    self = [super init];
    
    // This check serves to make sure that a non-NSDictionary object
    // passed into the model class doesn't break the parsing.
    if (self && [dict isKindOfClass:[NSDictionary class]]) {
            self.result = [Result modelObjectWithDictionary:[dict objectForKey:kBaseClassResult]];
            self.errorCode = [[self objectOrNilForKey:kBaseClassErrorCode fromDictionary:dict] doubleValue];
            self.reason = [self objectOrNilForKey:kBaseClassReason fromDictionary:dict];

    }
    
    return self;
    
}

- (NSDictionary *)dictionaryRepresentation {
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:[self.result dictionaryRepresentation] forKey:kBaseClassResult];
    [mutableDict setValue:[NSNumber numberWithDouble:self.errorCode] forKey:kBaseClassErrorCode];
    [mutableDict setValue:self.reason forKey:kBaseClassReason];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description  {
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict {
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}


#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];

    self.result = [aDecoder decodeObjectForKey:kBaseClassResult];
    self.errorCode = [aDecoder decodeDoubleForKey:kBaseClassErrorCode];
    self.reason = [aDecoder decodeObjectForKey:kBaseClassReason];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeObject:_result forKey:kBaseClassResult];
    [aCoder encodeDouble:_errorCode forKey:kBaseClassErrorCode];
    [aCoder encodeObject:_reason forKey:kBaseClassReason];
}

- (id)copyWithZone:(NSZone *)zone {
    BaseClass *copy = [[BaseClass alloc] init];
    
    
    
    if (copy) {

        copy.result = [self.result copyWithZone:zone];
        copy.errorCode = self.errorCode;
        copy.reason = [self.reason copyWithZone:zone];
    }
    
    return copy;
}


@end
