/* group.m,
 *
 * Group units together for things like cargos so that we know when
 * all of them are dead and then spawn a powerup.
 */

#include <assert.h>
#include "group.h"
#include "linklist.h"


static List *group_list;


@implementation UnitGroup
- (id) initWithID:(int)num
{
    [super init];
    group_id = num;
    member_count = 1;
    return self;
}

- (int) groupID { return group_id; }
- (void) incrementGroupRef { member_count++; }

- (BOOL) dropGroupRef
{
    member_count--;
    return (member_count == 0);
}
@end

UnitGroup *getGroupRef(int group_id)
{
    ListIterator *it;
    UnitGroup *group;

    foreach (it, group_list) {
        group = [it getItem];
        if ([group groupID] == group_id) {
            [group incrementGroupRef];
            return group;
        }
    }

    /* No group found with this id.  Create a new group. */
    group = [[UnitGroup alloc] initWithID:group_id];
    [group_list insertItem:group];

    return group;
}

void unit_group_init(void)
{
    group_list = [LIST_NEW];
    assert(group_list);
}

void unit_group_shutdown(void)
{
    if (group_list)
        group_list = [group_list free];
}
