/* hunter-seeker.h
 *
 * Little homing bastards that are launched out of guns.
 */

#include <math.h>
#include "common.h"
#include "rotate.h"
#include "seborrhea/container-animation.h"
#include "unit-seeking.h"
#include "units/hunter-seeker.h"


#define LAUNCH_SPEED	4.0
#define NORMAL_SPEED	2.0
#define SLOWDOWN_RATE	0.2


static SebFile *hunter_sebum;
static SebAnimation *open_anim;


@implementation HunterSeeker
+ (BOOL) loadData
{
    hunter_sebum = [SebFile new];
    if (not [hunter_sebum loadSebumDirectory:"data/hunter-seeker"])
	return NO;

    open_anim = (SebAnimation *)[hunter_sebum getSebumByName:"body"];
    return YES;
}

+ (void) shutdown
{
    FREE_SEBFILE(hunter_sebum);
    open_anim = nil;
}

- init
{
    [super init];

    health = 3;
    speed = LAUNCH_SPEED;
    activate_y = 15;	     /* Distance to travel before tracking. */

    frame_tics = frame_delay = 10;

    sprite = [open_anim getFrame:0];
    shadow = [hunter_sebum getSebumByName:"shadow"];
    w = 21;
    h = 7;
    rotatable_unit = YES;
    still_animating = YES;

    chunk_colours = CHUNK_GREEN;
    return self;
}

- (int) update
{
    if (still_animating) {
        if (--frame_tics <= 0) {
	    frame = [open_anim nextFrame:frame];
	    if (frame > 0) {	/* Don't loop. */
		sprite = [open_anim getFrame:frame];
		frame_tics = frame_delay;
	    }
	    else
		still_animating = NO;
        }
    }

    return [super update];
}

- (void) move
{
    if (activate_y > 0) {
	activate_y--;
	return [super move];
    }

    if (speed > NORMAL_SPEED)
	speed -= SLOWDOWN_RATE;

    if (!target || !unit_exists(target, ALLY_LIST))
	target = FIND_CLOSEST_ALLY(x, y);

    if (target) {
	double theta = angle_towards_unit(x, y, target);
	limited_rotate(&angle, theta, deg2rad(2.0));
	simplify_angle(&angle);
    }

    [super move];
}
@end
