//
//  MonsterDatabase.m
//  longspear
//
//  Created by Niko Matsakis on Fri Jun 18 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

#import "MonsterDatabase.h"
#import "Entity.h"

struct DefaultMonster
{
    NSString *name;
    NSString *ac;
    NSString *hp;
    NSString *cr;
    NSString *initiative;
    NSString *attacks;
    NSString *damage;
    NSString *saves;
    NSString *comments;
};

static struct DefaultMonster monster_data[] = {
#include "MonstersDatabaseDefn.h"
};

NSArray *
DefaultMonsterDatabase ()
{
    int i, monster_count = sizeof (monster_data) / sizeof (struct DefaultMonster);
    
    NSMutableArray *result = [[[NSMutableArray alloc] initWithCapacity:monster_count] autorelease];
 
    for (i = 0; i < monster_count; i++) {
        struct DefaultMonster *monster = monster_data+i;
        Entity *entity = [[[Entity alloc] initWithBase:nil notifyObject:nil] autorelease];
        [entity setFieldNamed:kNAME to:monster->name];
        [entity setFieldNamed:kARMORCLASS to:monster->ac];
        [entity setFieldNamed:kHITPOINTS to:monster->hp];
        [entity setFieldNamed:kCR to:monster->cr];
        [entity setFieldNamed:kINITSCORE to:monster->initiative];
        [entity setFieldNamed:kATTACKS to:monster->attacks];
        [entity setFieldNamed:kDAMAGE to:monster->damage];
        [entity setFieldNamed:kCOMMENTS to:monster->comments];
        [entity setfieldNamed:kSAVES to:monster->saves];
        [result addObject:entity];
    }
    
    return result;
}

void AddSortedMonster (NSMutableArray *array, Entity *monster)
{
    // Find the right place to put the monster so that they
    // stay in alphabetical order.  Remove any monsters
    // with the same name. 
    NSMutableArray *db = [[[NSMutableArray alloc] initWithArray:MonsterDatabase()] autorelease];
    int i, cnt = [db count];
    NSString *newname = [monster fieldAsString:kNAME];
    for (i = 0; i < cnt; i++) {
        // Stop at the first monster whose name compares as "greater"
        // than this name.
        Entity *dbmon = [db objectAtIndex:i];
        NSString *dbnm = [dbmon fieldAsString:kNAME];
        NSComparisonResult res = [newname caseInsensitiveCompare:dbnm];
        if (res == NSOrderedAscending)
            break;
        if (res == NSOrderedSame) {
            // if we find one with the same name remove it, then stop because
            // this is the right spot:
            [db removeObjectAtIndex:i];
            cnt--;
            break;
        }
    }
    
}