/* firefly.m,
 *
 * A arctan-shaped path following ship with four guns.
 */

#include <allegro.h>
#include <math.h>
#include "common.h"
#include "projectiles/plasma.h"
#include "seborrhea/seborrhea.h"
#include "units/firefly.h"


static SebFile *firefly_sebum;
static SebAnimation *fire_outer, *fire_inner;


@implementation FireFly
+ (BOOL) loadPrerequisites { return LOAD_PROJECTILE_DATA_FOR(Plasma); }

+ (BOOL) loadData
{
    firefly_sebum = [SebFile new];
    if (not [firefly_sebum loadSebumDirectory:"data/firefly"])
	return NO;

    fire_outer = (SebAnimation *)[firefly_sebum getSebumByName:"fire-outer"];
    fire_inner = (SebAnimation *)[firefly_sebum getSebumByName:"fire-inner"];
    return YES;
}

+ (void) shutdown
{
    FREE_SEBFILE(firefly_sebum);
    fire_outer = nil;
    fire_inner = nil;
}

- init
{
    [super init];

    health = 4;
    speed = 1.5;
    the_way = (SebSpline *)[firefly_sebum getSebumByName:"path"];
    activate_y = -30;

    sprite = [[SebAnimator new] setAnimation:fire_outer];
    shadow = [firefly_sebum getSebumByName:"shadow"];
    w = [sprite width];
    h = [sprite height];
    rotatable_unit = YES;

    /* Firing. */
    projectile = [Plasma class];
    shot_delay = 40;
    wave_delay = 70;
    shots_per_wave = 2;

    flags |= FLAG_FIRING_ENABLED;
    chunk_colours = CHUNK_RED;
    return self;
}

- (void) fireProjectiles
{
    int dist = inner_barrel ?  8 : 13;
    double deltax, deltay;

    deltax =  dist*sin(angle) + 20*sin(angle + M_PI_2);
    deltay =  dist*cos(angle) + 20*cos(angle + M_PI_2);
    [spawn_projectile(projectile, x+deltax, y+deltay, NO) setAngle:angle];

    deltax = -dist*sin(angle) + 20*sin(angle + M_PI_2);
    deltay = -dist*cos(angle) + 20*cos(angle + M_PI_2);
    [spawn_projectile(projectile, x+deltax, y+deltay, NO) setAngle:angle];

    if (inner_barrel)
	sprite = [(SebAnimator *)sprite setAnimation:fire_inner];
    else
	sprite = [(SebAnimator *)sprite setAnimation:fire_outer];
    inner_barrel = !inner_barrel;
}

- (void) fire
{
    if (--fire_tics > 0)
	return;
	
    [self fireProjectiles];

    if (++current_shot_number >= shots_per_wave) {
	current_shot_number = 0;
	fire_tics = wave_delay;
    }
    else
	fire_tics = shot_delay;
}

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

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

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

    return self;
}
@end
