#include "weather.h"
#include "globals.h"
#include "mymath.h"
#include "camera.h"
#include "map.h"


GameWeatherClass *GameWeather;


const Vec2D SnowDirection(0.0, 0.4);

void WeatherParticle::Update() {
  if (life > 0) {
    if (type == WEATHER_PARTICLE_TYPE_SNOW) {
      if (d) {
        dir += 0.01;
        if (dir > 0.5) d=false;
      }
      else {
        dir -= 0.01;
        if (dir < 0.5) d=true;
      }
      pos+=SnowDirection.Normalized();
      if (d) pos+=Vec2D(0.6, 0);
      else pos-=Vec2D(0.6, 0);
    }
  }
}

void WeatherParticle::Draw() {
  float fact;
  if (life > 0) {
    Vec2D cpos;
    cpos.x = (int)pos.x - RSW(Camera_X);
    cpos.y = (int)pos.y - RSH(Camera_Y);

    if (!ripple) {

      while (cpos.x < -10) cpos.x += SCREEN_W;
      while (cpos.x > SCREEN_W+10) cpos.x -= SCREEN_W;

      while (cpos.y < -10) cpos.y += SCREEN_H;
      while (cpos.y > SCREEN_H+10) cpos.y -= SCREEN_H;

    }

    if (type == WEATHER_PARTICLE_TYPE_SNOW) {
      fact = 1.0 - (((cpos.y) / 1000.0));
      if (fact < 0) fact = 0;
      DRAW_TRANSFORMED(snow_bit, cpos.x, cpos.y, RSW(length), RSH(length), 0, 0);
    }
  }
}


void GameWeatherClass::SetParticle(WeatherParticle *p) {
  float x, y, l;
  if (type == WEATHER_TYPE_SNOWY) {
    x = RSW(Camera_X) - RSW(200);
    y = RSW(Camera_Y) - RSW(200);

    x += randn(SCREEN_W*1.2);
    y += randn(SCREEN_H*1.2);

    l = randn(2);

    p->SetTo(x, y, l);
    p->SetLife(randn(80) + 250);
    p->SetFactor((float)randn(4) / 10.0);
    p->SetType(WEATHER_PARTICLE_TYPE_SNOW);
  }
}

void GameWeatherClass::Update() {
  std::vector<WeatherParticle>::iterator it;
  for (it=particles.begin(); it!=particles.end(); it+=1) {
    (*it).Update();
    if ((*it).GetLife() <= 0) SetParticle(&(*it));
  }
}
