#include "stdafx.h"
#include "Layer2UnitData.h"
#include "Actions/GroupTacticalAction.h"
#include "../Layer2Actions.h"

bool Layer2UnitData::proposeAction(GroupTacticalAction* action, bool force)
{
  assert(!m_unit->getType().isBuilding()); // At the moment we do not reserve buildings

  // This assert can actually fail (comically) when a unit is being transferred to some action, but is 
  // again (recursively) transferred to another one during the initial getGroup()->remove()
  //assert(unitData.m_currentAction == NULL || unitData.m_currentAction->getGroup()->contains(unit));

  bool accepted = false;
  if (m_currentAction == NULL)
  {
    m_currentAction = action;
    accepted = true;
  }
  else if (m_currentAction != action)
  {
    if (force || action->getPriority() > m_currentAction->getPriority())
    {
      GroupTacticalAction* previousAction = m_currentAction;
      m_currentAction = action;
      previousAction->removeUnit(m_unit);
      // "m_currentAction" may no longer be == to "action" since someone else may have grabbed it
      // during the "previousAction->removeUnit(unit)" events generated
      if (m_currentAction == action)
      {
        accepted = true;
      }
    }
  }
  return accepted;
}

void Layer2UnitData::removeAction(GroupTacticalAction* action)
{
  if (m_currentAction == action)
  {
    m_currentAction = NULL;
    if (!isDestroyed())
    {
      Layer2Actions::getInstance().getUnitIdleEvent().raise(m_unit, action);
    }
  }
  // Else another action has preempted this action
}
