#include "Ufo.h"
#include "Level.h"
#include "LD.h"



Ufo::Ufo()
{
  TexSection = LD::TEX_UFO_1;
  Type = LD::GO_UFO;
  Color = 0xffffffff;
  m_AnimPos = 0.0f;
  m_UfoSpeed = 60.0f;
  HP = 5;
}



void Ufo::Update( Level& theLevel, float ElapsedTime )
{
  m_AnimPos += ElapsedTime;

  switch ( (int)( fmodf( m_AnimPos, 0.5f ) / 0.125f ) )
  {
    case 0:
    case 2:
      TexSection = LD::TEX_UFO_1;
      break;
    case 1:
      TexSection = LD::TEX_UFO_2;
      break;
    case 3:
      TexSection = LD::TEX_UFO_3;
      break;
  }

  LD::PointF    curPos( Position.x + FractPos.x, Position.y + FractPos.y );

  float     distance = m_UfoSpeed * ElapsedTime;
  float     totalDistance = ( m_TargetPos - curPos ).length();

  if ( distance >= totalDistance )
  {
    // arrived at target
    Position.set( (int)m_TargetPos.x, (int)m_TargetPos.y );
    FractPos.clear();

    m_TargetPos.set( ( rand() % 32 ) * 32 + 16.0f, ( rand() % 24 ) * 32 + 16.0f );

    theLevel.SetTile( Position.x / 32, Position.y / 32, 5 );
    theApp.PlaySoundA( LD::SOUND_LOST_TILE );
  }
  else
  {
    LD::PointF    speedVector = ( m_TargetPos - curPos );
    speedVector /= speedVector.length();

    LD::PointF    delta = speedVector * distance;

    FractPos += delta;
    AdjustFractPos();
  }

  /*
  LD::Point     tilePos = TilePos();

  if ( ( tilePos.x >= 0 )
  &&   ( tilePos.x < 32 )
  &&   ( tilePos.y >= 0 )
  &&   ( tilePos.y < 24 ) )
  {
    if ( theLevel.Grid[tilePos.x][tilePos.y] > 0 )
    {
      --theLevel.Grid[tilePos.x][tilePos.y];
      RemoveMe = true;

      theLevel.Score += 10;

      if ( theLevel.Grid[tilePos.x][tilePos.y] == 0 )
      {
        // remove grid
        theApp.PlaySoundA( LD::SOUND_WIN_TILE );

        theLevel.CheckCloud( tilePos.x - 1, tilePos.y - 1, tilePos.x, tilePos.y );
        theLevel.CheckCloud( tilePos.x, tilePos.y - 1, tilePos.x + 1, tilePos.y );
        theLevel.CheckCloud( tilePos.x - 1, tilePos.y, tilePos.x, tilePos.y + 1 );
        theLevel.CheckCloud( tilePos.x, tilePos.y, tilePos.x + 1, tilePos.y + 1 );
      }
    }
  }*/

  FractPos += Speed * ElapsedTime;
  AdjustFractPos();

  Unit::Update( theLevel, ElapsedTime );
}



void Ufo::Display( IDirect3DDevice8* pDevice )
{
  theApp.RenderTextureSection2d( Position.x - 24, Position.y - 24, theApp.m_TexSec[TexSection], Color );
}
