//
//  OperCtx.m
//
//  Created by Z  on 16/4/12
//  Copyright (c) 2016 __MyCompanyName__. All rights reserved.
//

#import "OperCtx.h"
#import "Operator.h"


NSString *const kOperCtxOperator = @"operator";
NSString *const kOperCtxTime = @"time";
NSString *const kOperCtxDomain = @"domain";


@interface OperCtx ()

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

@end

@implementation OperCtx

@synthesize operator = _operator;
@synthesize time = _time;
@synthesize domain = _domain;


+ (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.operator = [Operator modelObjectWithDictionary:[dict objectForKey:kOperCtxOperator]];
            self.time = [self objectOrNilForKey:kOperCtxTime fromDictionary:dict];
            self.domain = [self objectOrNilForKey:kOperCtxDomain fromDictionary:dict];

    }
    
    return self;
    
}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:[self.operator dictionaryRepresentation] forKey:kOperCtxOperator];
    [mutableDict setValue:self.time forKey:kOperCtxTime];
    [mutableDict setValue:self.domain forKey:kOperCtxDomain];

    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.operator = [aDecoder decodeObjectForKey:kOperCtxOperator];
    self.time = [aDecoder decodeObjectForKey:kOperCtxTime];
    self.domain = [aDecoder decodeObjectForKey:kOperCtxDomain];
    return self;
}

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

    [aCoder encodeObject:_operator forKey:kOperCtxOperator];
    [aCoder encodeObject:_time forKey:kOperCtxTime];
    [aCoder encodeObject:_domain forKey:kOperCtxDomain];
}

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

        copy.operator = [self.operator copyWithZone:zone];
        copy.time = self.time;
        copy.domain = [self.domain copyWithZone:zone];
    }
    
    return copy;
}


@end
