#include <Xtreme/XRenderer.h>

#include ".\BirdiesRevenge.h"
#include ".\Bonus.h"
#include ".\Level.h"



Bonus::Bonus()
{
  m_Type = Birdie2::UT_BONUS;

  m_MovementBounds.set( 0, 0, 40, 40 );
  m_CollisionBounds.set( 0, 0, 40, 40 );

  m_Floating   = false;
  m_Done       = false;
  m_MakeDiamond = false;

  m_HitCount    = 4 + rand() % 3;
  m_LifeTime    = 7.5f;
  m_YSpeed      = -30;
  m_Value       = 1;
}



void Bonus::Update( Level& Level, const GR::f32 fElapsedTime )
{
  if ( !m_Done )
  {
    m_Speed.x = m_FaceLeft ? -5 : 5;

    //++m_YSpeed;
    //m_ptSpeed.y = m_YSpeed;
  }
  Unit::Update( Level, fElapsedTime );
}



void Bonus::ChangeToPickup()
{
  if ( m_MakeDiamond )
  {
    int     diamondType = ( m_Position.x / ( 800 / 7 ) );
    m_BonusImage = Misc::Format( "Diamond.%1%" ) << diamondType + 1;
  }
  SetImage( m_BonusImage );
}



void Bonus::ProcessEvent( Level& Level, const eUnitEvent& Event )
{
  switch ( Event )
  {
    case Unit::ET_BLOCKED_LEFT:
      m_FaceLeft = false;
      HitWall();
      break;
    case Unit::ET_BLOCKED_RIGHT:
      m_FaceLeft = true;
      HitWall();
      break;
    case Unit::ET_BLOCKED_UP:
      m_Jumping = false;
      m_JumpSpeed = 0;
      m_Speed.y = 0;
      m_OnGround = false;
      HitWall();
      break;
    case Unit::ET_FALL_END:
    case Unit::ET_BLOCKED_DOWN:
      HitWall();
      m_Speed.x = 0;
      if ( !m_Done )
      {
        Jump( 30 );
      }
      break;
    case Unit::ET_FALL_START:
      if ( m_HitCount )
      {
        m_HitCount--;
        if ( m_HitCount == 0 )
        {
          m_Done = true;
          m_Floating = false;
          m_LifeTime = 10.0f;
          m_Speed.x = 0;
          ChangeToPickup();
        }
      }
      break;
  }
  Unit::ProcessEvent( Level, Event );
}



void Bonus::HitWall()
{
  if ( m_HitCount )
  {
    m_HitCount--;
    theApp.SoundClass()->Play( theApp.Sound( "HitWall" ) );
    if ( m_HitCount == 0 )
    {
      m_Done = true;
      m_Floating = false;
      m_LifeTime = 10.0f;
      m_Speed.x = 0;
      ChangeToPickup();
    }
  }
}