//
//  RelationKey.m
//  ArmorP3V1
//

#import "RelationKey.h"
#import "SkillSet.h"
#import "PSMutex.h"

@implementation RelationKey

@synthesize key = _key;
@synthesize count = _count;

-(id)init {
    self = [super init];
    if (self) {
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

-(id)copyWithZone:(NSZone *)zone {
    [self retain];
    return self;
}

-(NSUInteger)hash {
    int hash;
    for (int i = 0; i < _count; ++ i) {
        hash += _key[i];
    }
    return hash;
}

-(BOOL)isEqual:(id)object {
    if (self == object) {
        return TRUE;
    }
    RelationKey* key2 = object;
    
    if ([RelationKey compareRelationKey:self :key2] == 0) {
        return TRUE;
    }
    
    return FALSE;
}

-(void)dealloc {
    free(_key);
    [super dealloc];
}

-(void)set:(SkillSet*)diffSkills {
    if (_key == nil || _count != diffSkills.count) {
        if (_key != nil) free(_key);
        _key = calloc(sizeof(BOOL), diffSkills.count);
        _count = diffSkills.count;
    }
}

-(RelationKey*)makeCopy {
    RelationKey* another = [[RelationKey alloc]init];
    another.key = calloc(sizeof(BOOL), _count);
    another.count = _count;
    for (int i = 0; i < _count; ++ i) {
        another.key[i] = _key[i];
    }
    return another;
}

+(int)compareRelationKey:(id)a: (id)b {
    RelationKey* that = a;
    RelationKey* target = b;
    
    if (that.count != target.count) {
        if (that.count < target.count) return 1;
        return -1;
    }
    for (int i = 0; i < that.count; ++ i) {
        if (that.key[i] != target.key[i]) {
            if (that.key[i] < target.key[i]) return 1;
            return -1;
        }
    }
    return 0;
}

@end
