#include ".\RedMask.h"
#include ".\Level.h"
#include ".\GetEmGood.h"
#include "PlayState.h"



RedMask::RedMask() :
  m_NumTilesToMove( 0 )
{
  m_Type = Pac::UT_RED_MASK;
  SetAnimation( "RedMask.Move" );
  m_MoveSpeed = 8;

  m_HP = 8;

  m_DisplayOffset.set( -( 48 - 16 ) / 2, -( 21 - 16 ) / 2 - 18 );
}



void RedMask::UpdateFixed( PlayState& State )
{
  TiledMover::UpdateFixed( State );
}



void RedMask::OnArrivedAtTile( PlayState& State )
{
  TiledMover::OnArrivedAtTile( State );
  if ( m_NumTilesToMove )
  {
    --m_NumTilesToMove;
    if ( State.Level.CanMove( this, m_Position, m_MoveDir ) )
    {
      return;
    }
    m_NumTilesToMove = 0;
  }

  bool          canMoveLeft = State.Level.CanMove( this, m_Position, Pac::DIR_W );
  bool          canMoveRight = State.Level.CanMove( this, m_Position, Pac::DIR_E );
  bool          canMoveUp = State.Level.CanMove( this, m_Position, Pac::DIR_N );
  bool          canMoveDown = State.Level.CanMove( this, m_Position, Pac::DIR_S );

  std::map<Pac::eDir,int>     possibleDirections;

  if ( canMoveLeft )
  {
    possibleDirections[Pac::DIR_W] = 0;
  }
  if ( canMoveRight )
  {
    possibleDirections[Pac::DIR_E] = 0;
  }
  if ( canMoveUp )
  {
    possibleDirections[Pac::DIR_N] = 0;
  }
  if ( canMoveDown )
  {
    possibleDirections[Pac::DIR_S] = 0;
  }
  if ( possibleDirections.empty() )
  {
    m_MoveDir = Pac::DIR_NONE;
    return;
  }
  if ( possibleDirections.size() == 1 )
  {
    m_MoveDir = possibleDirections.begin()->first;
    return;
  }
  // we have to determine by preference
  int     highestPoints = 0;

  std::map<Pac::eDir, int>::iterator    itP( possibleDirections.begin() );
  while ( itP != possibleDirections.end() )
  {
    itP->second = DetermineMovementPoints( itP->first );

    if ( itP->second > highestPoints )
    {
      highestPoints = itP->second;
    }

    ++itP;
  }

  std::set<Pac::eDir>   potentialDirs;
  itP = possibleDirections.begin();
  while ( itP != possibleDirections.end() )
  {
    if ( itP->second == highestPoints )
    {
      potentialDirs.insert( itP->first );
    }

    ++itP;
  }

  int     randDir = rand() % potentialDirs.size();

  std::set<Pac::eDir>::iterator itPD = potentialDirs.begin();
  std::advance( itPD, randDir );

  m_MoveDir = *itPD;

  m_NumTilesToMove = 1 + rand() % 8;
}



int RedMask::DetermineMovementPoints( Pac::eDir Dir )
{
  return 1;
}



void RedMask::ProcessEvent( PlayState& State, const eUnitEvent& Event )
{
  TiledMover::ProcessEvent( State, Event );
  switch ( Event )
  {
    case ET_BLOCKED_UP:
      break;
    case ET_FALL_START:
      break;
    case ET_FALL_END:
      break;
    case ET_ENTER_PLATFORM:
      break;
    case ET_LEAVE_PLATFORM:
      break;
    case ET_DIE:
      break;
  }
}



void RedMask::OnLoad( PlayState& State )
{
  m_StartPosition = m_Position;
}



