#include "stdafx.h"
#include "UnitCarefulAttackBehavior.h"
#include "../../../Layer1FSM.h"
#include "../../DodgeBehavior.h"

///////////////////////////////////////////////////
// Unit in moving State

UnitCarefulAttackBehavior::Moving::Moving(UnitCarefulAttackBehavior& behavior)
  : BehaviorStateT(behavior)  
  , m_update(*this, Scheduler::FSM_SCHEDULING_PRIORITY,10,10)
  , m_transition(
	  *this,
	  NotNull(&behavior.m_target),
	  NoTransitionAction(),
	  behavior.m_safeState)
  , m_events(m_update)
  , m_transitions(m_transition)
{
}

void UnitCarefulAttackBehavior::Moving::onEnter()
{
}

void UnitCarefulAttackBehavior::Moving::onExit()
{
}

///////////////////////////////////////////////////
// Unit in safe State

UnitCarefulAttackBehavior::Safe::Safe(UnitCarefulAttackBehavior& behavior)
  : BehaviorStateT(behavior)  
  , m_update(*this, Scheduler::FSM_SCHEDULING_PRIORITY, 10, 10)
  //, m_attackAction(*this)
  , m_transition(
	  *this,
	  ShouldBeDodging(HasCriticalHealth(behavior.m_unit), InDanger(behavior.m_unit)),
	  NoTransitionAction(),
	  behavior.m_criticalState)
  , m_events(m_update)
  , m_transitions(m_transition)
{
}

void UnitCarefulAttackBehavior::Safe::onEnter()
{
	orderAttack();
}

void UnitCarefulAttackBehavior::Safe::orderAttack()
{
  Layer1FSM::getInstance().getArbitrator().
    submitCommand(m_context.m_unit, AttackUnitCommand(*this, m_context.m_target), Arbitration::ActionImportance(m_context));
}

void UnitCarefulAttackBehavior::Safe::onExit()
{
}

///////////////////////////////////////////////////
// Unit in critical State

UnitCarefulAttackBehavior::Critical::Critical(UnitCarefulAttackBehavior& behavior)
  : BehaviorStateT(behavior)
  //, m_moveCommand(*this)
  //, m_location(m_context.m_unit)
  //, m_enemyUnitsInLocationRequest(m_location, behavior.m_group)
  //, m_enemyUnitsInLocationEvent(m_enemyUnitsInLocationRequest, Scheduler::FSM_SCHEDULING_PRIORITY, 12, 12)
  , m_update(*this, Scheduler::FSM_SCHEDULING_PRIORITY, 12, 12)
  , m_transitionToSafeState(
      *this,
      NoCondition(),
      NoTransitionAction(), 
      behavior.m_safeState)
  , m_events(m_update)
  , m_transitions(m_transitionToSafeState)
{
}

void UnitCarefulAttackBehavior::Critical::onEnter()
{
  //log("dodging");
  if(m_context.m_group->size() > 1)
  {
    BWAPI::Position destination = DodgeBehavior::getSafeDodgePosition(m_context.m_unit);
	  Layer1FSM::getInstance().getArbitrator().submitCommand(m_context.m_unit, MoveCommand(*this, destination), Arbitration::ActionImportance(m_context));
  }
}

void UnitCarefulAttackBehavior::Critical::onExit()
{
}
