/* cargo.m,
 *
 * Cargos are units which spawn a primary weapon powerup when the
 * entire group has been destroyed.  "CargoHealth" should be used when
 * it contains a health powerup (for urgency purposes).
 */

#include <math.h>
#include "common.h"
#include "powerup.h"
#include "seborrhea/seborrhea-allegro.h"
#include "seborrhea/seborrhea.h"
#include "unit-mapextras.h"
#include "units/all-units.h"
#include "units/cargo.h"


static SebFile *cargo_sebum;


@implementation Cargo
+ (BOOL) loadData
{
    if (cargo_sebum)		/* Don't load twice. */
	return YES;

    cargo_sebum = [SebFile new];
    return [cargo_sebum loadSebumDirectory:"data/cargo"];
}

+ derive_shutdown(cargo_sebum);

- init
{
    [super init];

    speed = 3.0;
    the_way = (SebSpline *)[cargo_sebum getSebumByName:"path"];
    activate_y = -150;

    sprite = [cargo_sebum getSebumByName:"cargo"];
    shadow = [cargo_sebum getSebumByName:"shadow"];
    w = [sprite width];
    h = [sprite height];
    rotatable_unit = YES;

    group_num = 0;
    group = NULL;

    /* Default is spawn a primary weapon powerup. */
    flags = FLAG_DEATH_SPAWN_PRIMARY_POWERUP;
    return self;
}

- (id) setX:(double)x_ Y:(double)y_
{
    [super setX:x_ Y:y_];

    /* We want the path to originate 30 pixels to the left/right of the screen. */
    path_x_displacement = -30;

    /* This is really just to look good in the map editor. */
    if (x < screen_w / 2)
	angle = 0;
    else
	angle = M_PI;

    return self;
}

- (void) die
{
    /* If still units in the group, don't spawn any powerups. */
    if (group && ([group dropGroupRef] == NO))
	flags = 0;

    [super die];
}

	/* Load/Save.  Format: group_num;x;y;a[;flags]*/
- (void) importUnitProperties:(char *)str
{
    char str2[1024];

    sscanf(str, "%d;%s", &group_num, str2);
    [super importUnitProperties:str2];

    /* Find the appropriate group to add it to. */
    group = getGroupRef(group_num);
}

- (char *) exportUnitProperties:(char *)str
{
    char str2[1024] = "\0";

    [super exportUnitProperties:str2];
    snprintf(str, sizeof(str2), "%d;%s", group_num, str2);
    return str;
}

	/* For use in map editor only! */
- (void) drawMapEditorExtras:(BITMAP *)dest
{
    [super drawMapEditorExtras:dest];
    draw_group_num(dest, x, y, group_num);
}

	/* Protocol stuff. */
- derive_setGroup(group_num);
@end

/*------------------------------------------------------------*/

@implementation CargoHealth
- init
{
    [super init];

    sprite = [cargo_sebum getSebumByName:"cargo-health"];

    /* This unit is supposed to be used for health powerups only to
       differentiate it from other cargos. */
    flags = FLAG_DEATH_SPAWN_HEALTH_POWERUP;
    return self;
}

	/* Data sharing tweaks. */
+ (BOOL) loadData { return LOAD_UNIT_DATA_FOR(Cargo, YES); }
+ (void) shutdown {}
@end
