//
//  MMOItem.m
//  SFS2X
//
//  Created by Lapo on 28/11/13.
//  Copyright (c) 2013 A51 Integrated | http://a51integrated.com. All rights reserved.
//

#import "MMOItem.h"
#import "ArrayUtil.h"
#import "ISFSArray.h"
#import "MMOItemVariable.h"

@implementation MMOItem
{

@protected
    NSMutableDictionary* _variables;

}

@synthesize id = _id;
@synthesize aoiEntryPoint = _aoiEntryPoint;

+(id<IMMOItem>) fromSFSArray:(id<ISFSArray>)array
{
    // Create the MMO Item with the server side ID (Index = 0 of the SFSArray)
    id<IMMOItem> item = [[MMOItem alloc] initWithId:[array getInt:0]];
    
    // Decode ItemVariables (Index = 1 of the SFSArray)
    id<ISFSArray> encodedVars = [array getSFSArray:1];
    
    for (int i = 0; i < [encodedVars size]; i++)
    {
        [item setVariable:[MMOItemVariable fromSFSArray:[encodedVars getSFSArray:i]]];
    }
    
    return item;
}

-(id) initWithId:(NSInteger)itemId
{
    self = [super init];
    
    if (self)
    {
        _id = itemId;
        _variables = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

-(id <IMMOItemVariable>)getVariable:(NSString *)varName
{
    @synchronized (_variables)
    {
        return [_variables objectForKey:varName];
    }
}

-(NSArray*)getVariables
{
    @synchronized (_variables)
    {
        return [ArrayUtil objToArray:_variables];
    }
}


-(BOOL)containsVariable:(NSString *)varName
{
    @synchronized (_variables)
    {
        return ([_variables objectForKey:varName] != nil);
    }
}

-(void)setVariables:(NSArray*) variables
{
    @synchronized (_variables)
    {
        for (id itemVar in variables)
        {
            if ([itemVar conformsToProtocol:@protocol(IMMOItemVariable)])
                [self setVariable: itemVar];
        }
        
    }
}

-(void)setVariable:(id <IMMOItemVariable>)var
{
    if (var != nil)
    {
        @synchronized (_variables)
        {
            // Delete if null-ified
            if ([var isNull])
                [_variables removeObjectForKey:[var name]];
            
            else
                [_variables setObject:var forKey:[var name]];
        }
	}
}

@end
