#include "globals.h"
#include "projectile.h"
#include "person.h"
#include "tdsound.h"
#include "map.h"
#include "particle.h"
#include "camera.h"

std::deque<Projectile *> projectiles;

void AddProjectile(float x, float y, float s, float d, float lf, bool sd, Vec2D dr, int type) {
  Projectile *p;

  p=new Projectile(s, d, lf, sd, dr, type);
  p->SetPosition(x, y);

  if (type == PROJECTILE_TYPE_SNOWBALL) {
    p->SetSize(10, 10);
    p->LoadGraphics("Projectiles/Snowball");
  }

  projectiles.push_back(p);
}

void UpdateProjectiles() {
  std::deque<Projectile *>::iterator p;
  for (p=projectiles.begin(); p!=projectiles.end(); p+=1) {
    (*p)->Update();
  }

  std::deque<Projectile *> oldlist;
  std::deque<Projectile *>::iterator it;
  oldlist.clear();
  for (it=projectiles.begin(); it != projectiles.end(); it += 1) {
    if (!(*it)->Dead()) oldlist.push_back((*it));
    else {
      delete (*it);
    }
  }
  projectiles.clear();
  for (it=oldlist.begin(); it != oldlist.end(); it += 1) {
    projectiles.push_back((*it));
  }
  oldlist.clear();
}


void DrawProjectiles() {
  std::deque<Projectile *>::iterator p;
  for (p=projectiles.begin(); p!=projectiles.end(); p+=1) {
    (*p)->Draw();
  }
}


void Projectile::UpdateGeneral() {
  x += dir.x*(speed*parb*DeltaTime);
  y += dir.y*(speed*parb*DeltaTime);

  if (!actual_map->IsFreeAbove(x, y)) {
    life=0;
  }

  life -= DeltaTime;

  if (life < 0) {
    CreateParticles();
    return;
  }

  parb += parb_dir*DeltaTime;
  if (parb < 0.5) {
    parb = 0.5;
    parb_dir *= -1;
  }
  if (parb > 1.0) parb = 1.0;

  std::deque<Person *>::iterator it;
  for (it=persons.begin(); it!=persons.end(); it+=1) {
      if (((*it)->IsMine() != my_side) && (!(*it)->IsUnconscious())) {
        if ((*it)->IsInRange(x, y, w)) {
          (*it)->Hit(damage);
          int i = randn(5)-1;
          ALLEGRO_SAMPLE *samp;
          samp = hit[i];
          play_3d_sample(samp, 1.2,1.0, ALLEGRO_PLAYMODE_ONCE, RSW(x), RSH(y));
          life=0;
          hitt=true;
          CreateParticles();
          break;
        }
      }
  }
}


void Projectile::CreateParticles() {
  int i;
  if (type == PROJECTILE_TYPE_SNOWBALL) {
    Vec2D dr;
    int sz;
    if (hitt) sz = randn(8);
    else sz = randn(3);
    for (int i=0;i!=sz; i+=1) {
      dr.x = randn(300)-150;
      dr.y = randn(300)-150;
      dr = dr.Normalized();
      float sp;
      sp = randn(100) / 10.0;

      AddParticle(randn(6)-1, x, y, sp, dr, 12);
    }
  }
}


void Projectile::Draw() {
  DrawGeneral();
  if (actual != NULL) {
    if (InsideScreen()) {
      DRAW_TRANSFORMED(actual->get_bit(), RSW(x-Camera_X), RSH(y-Camera_Y), rw + rw*(1.0-parb), rh + rh*(1.0-parb), angle, 0);
    }
  }
}
