#include ".\unit.h"
#include "LD.h"
#include "GSPlanet.h"



#define NULL 0



Unit::Unit() :
  m_RemoveMe( false ),
  m_X( 0 ),
  m_Y( 0 ),
  m_XFract( 0.0f ),
  m_YFract( 0.0f ),
  m_Angle( 0.0f ),
  m_Type( LD::UT_INVALID ),
  m_LifeTime( 0.0f ),
  m_SpeedX( 0.0f ),
  m_SpeedY( 0.0f ),
  m_Speed( 0.0f ),
  m_Life( 1 ),
  m_ShotDelay( 0.0f )
{
}



void Unit::Display( int OffsetX, int OffsetY )
{

  if ( m_Type == LD::UT_PARTICLE )
  {
    theApp.RenderTextureSectionRotatedScaled2d( m_X - OffsetX, m_Y - OffsetY, theApp.m_TexSec[m_Texture], m_Angle, m_LifeTime );
  }
  else
  {
    theApp.RenderTextureSectionRotated2d( m_X - OffsetX, m_Y - OffsetY, theApp.m_TexSec[m_Texture], m_Angle );
  }

}



void Unit::Update( CGSPlanet* pGSPlanet, const float ElapsedTime )
{

  Advance( m_Speed * ElapsedTime );
  if ( m_LifeTime > 0.0f )
  {
    m_LifeTime -= ElapsedTime;
    if ( m_LifeTime <= 0.0f )
    {
      m_LifeTime = 0.0f;
      m_RemoveMe = true;
    }
  }

  if ( m_ShotDelay > 0.0f )
  {
    m_ShotDelay -= ElapsedTime;
    if ( m_ShotDelay <= 0.0f )
    {
      m_ShotDelay = 0.0f;
    }
  }
  if ( m_Type == LD::UT_ENEMY_TURRET )
  {
    if ( m_ShotDelay == 0.0f )
    {
      if ( pGSPlanet->m_pPlayerUnit )
      {
        m_ShotDelay = 0.8f;
        float   angleToResource = 0.0f;
        if ( pGSPlanet->SafeDistance( pGSPlanet->m_pPlayerUnit->m_X, pGSPlanet->m_pPlayerUnit->m_Y, m_X, m_Y, angleToResource ) < 600.0f )
        {
          pGSPlanet->SpawnShot( this, 0.0f, 0.0f, 90.0f - angleToResource, LD::TEX_ENEMY_SHOT, 3, 340.0f );

          theApp.PlaySound( LD::SOUND_ENEMY_SHOT );
        }
      }
    }
  }

}



void Unit::Advance( float Distance )
{

  m_XFract -= sinf( 3.1415926f * m_Angle / 180.0f ) * Distance;
  m_YFract -= cosf( 3.1415926f * m_Angle / 180.0f ) * Distance;

  while ( m_XFract >= 1.0f )
  {
    m_X++;
    m_XFract -= 1.0f;
  }
  while ( m_XFract < 0.0f )
  {
    m_X--;
    m_XFract += 1.0f;
  }
  while ( m_YFract >= 1.0f )
  {
    m_Y++;
    m_YFract -= 1.0f;
  }
  while ( m_YFract < 0.0f )
  {
    m_Y--;
    m_YFract += 1.0f;
  }

}