//
//  SFSGlobalUserManager.m
//  SFS2X
//
//  Original development by Infosfer Game Technologies Ltd. | http://www.infosfer.com.
//
//  Maintained and developed by A51 Integrated.
//  Copyright 2012 A51 Integrated | http://a51integrated.com. All rights reserved.
//

#import "SFSGlobalUserManager.h"
#import "Logger.h"

@implementation SFSGlobalUserManager




-(id)initWithSfs:(SmartFox2XClient *)sfs {
	
	if ((self = [super initWithSfs:sfs])) {
		_roomRefCount = [NSMutableDictionary dictionary];        
	}

	return self;
}

-(void)addUser:(id <User>)user {
	
    [super _addUser:user];
    
	if ([_roomRefCount objectForKey:[NSNumber numberWithInt:(int)[user id]]] == nil)
    {
		[_roomRefCount setObject:[NSNumber numberWithInt:1] forKey:[NSNumber numberWithInt:(int)[user id]]];
	}
	
	else
    {
		int refCount = [(NSNumber *)[_roomRefCount objectForKey:[NSNumber numberWithInt:(int)[user id]]] intValue] + 1;
		[_roomRefCount setObject:[NSNumber numberWithInt:refCount] forKey:[NSNumber numberWithInt:(int)[user id]]];
	}
}

-(void)removeUser:(id <User>)user {
	
	if ([_roomRefCount objectForKey:[NSNumber numberWithInt:(int)[user id]]] != nil) {
		
		int refCount = [(NSNumber *)[_roomRefCount objectForKey:[NSNumber numberWithInt:(int)[user id]]] intValue];
		
		if (refCount < 1) {
			[_log warn:[NSString stringWithFormat:@"GlobalUserManager RefCount is already at zero. User: %@", user]];
		}
		
		refCount--;

		if (refCount == 0) {
			[super removeUser:user];
			[_roomRefCount removeObjectForKey:[NSNumber numberWithInt:(int)[user id]]];
		}
		
	}
	else {
		[_log warn:[NSString stringWithFormat:@"Can't remove User from GlobalUserManager. RefCount missing. User: %@", user]];
	}

}

@end
