/* turret.m,
 *
 * The spinning turret after a turret or tank is destroyed.
 */

#include <allegro.h>
#include <math.h>
#include "common.h"
#include "debris/explosion.h"
#include "debris/tank-debri.h"
#include "debris/turret.h"
#include "map.h"
#include "seborrhea/seborrhea-allegro.h"
#include "seborrhea/seborrhea.h"


@implementation TurretDebri
- init
{
    [super init];

    health = max_health = 50;
    speed = 1.5;
    omega = deg2rad(rnd(80, 100) / 10) * ((rand()%2 == 0) ? -1 : 1);
    in_space = [current_map stars];

    {				/* Velocity. */
	double theta = deg2rad(rnd(30, 150));
	xv = speed * cos(theta);
	yv = speed * sin(theta);
    }

    return self;
}

- (id) setAngle:(double)theta; { angle = theta; return self; }

- (void) draw:(BITMAP *)dest
{
    double scale;

    /* Fly up and explode in the air.  "Zero gravity!" */
    if (in_space)
	scale = 1.0 + 1.2*(max_health-health)/max_health;

    /* Fly up into the air and explode on the ground. */
    else
	scale = 1.0 + 1.2*sin(deg2rad(180 * health/max_health));

    pivot_scaled_sprite(dest, [(SebImageAllegro *)sprite bitmap],
			x-offsetX, y-offsetY, w/2, h/2,
			rad2fix(angle), ftofix(scale));
}

- (BOOL) mayStillInfluenceGameplay
{ 
    /* The size of the sprite can be stretched up to 2.2x. */
    int x_ = x-offsetX;
    int y_ = y-offsetY;
    
    if ((x_ + 2.2*w/2 < 0) || (x_ - 2.2*w/2 > screen_w) ||
	(y_ + 2.2*h/2 < 0) || (y_ - 2.2*h/2 > screen_h))
	return NO;
    return YES;
}

- (int) update
{
    if (health == max_health) {
	w = [sprite width];
	h = [sprite height];
    }

    health--;

    if (health <= 0) {
	play_explosion_sample(x);

	if (not in_space)
	    spawn_debris([TankDebri class], x, y, FLOOR_LAYER);
	spawn_debris([BigExplosion class], x, y, MEDIUM_LAYER);
	spawn_debris([BigExplosion class], x, y, MEDIUM_LAYER);
	spawn_debris([BigExplosion class], x, y, MEDIUM_LAYER);
	return THING_DEAD;
    }

    angle += omega;
    recalculate_velocity = NO;
    return [super update];
}
@end
