includefilename = "asset\\composition\\AIScript\\LordAICommon.lua" 
includefilename = SYSTEM.RelativeToAbsolutePath(includefilename)
dofile(includefilename)

function Init ()
  Enter_Idle()
end

function Enter_Idle()
  ARMY.SetBehavior(myArmyID, "Idle")
  STATE = "Idle"
  return 1
end

function Enter_Pursuit(GoalEnemyArmyID)
  Pursuit_Goal_ArmyID = GoalEnemyArmyID
  PursuitStateStartTime = TIME.GetGameNowTime()
  PursuitStateStartPositionX, PursuitStateStartPositionY = ARMY.GetPosition(myArmyID)

  ARMY.SetBehavior(myArmyID, "AttackLord")
  ARMY.SetGoal(myArmyID, "ARMY", Pursuit_Goal_ArmyID)

  STATE = "Pursuit"
  return 1
end

function Enter_Move1()
  ARMY.SetBehavior(myArmyID, "WalkTo")
  ARMY.SetGoalPosition(myArmyID, IdleStateEndPositionX, IdleStateEndPositionY)

  STATE = "Move1"
  return 1
end

function Enter_Capture(GoalTowerID)
  Capture_Goal_TowerID = GoalTowerID

  ARMY.SetBehavior(myArmyID, "Capturing")
  ARMY.SetGoal(myArmyID, "TOWER", Capture_Goal_TowerID)

  STATE = "Capture"
  return 1
end

function Exit_Idle()
  IdleStateEndPositionX, IdleStateEndPositionY = ARMY.GetPosition(myArmyID)
  return 1
end

function Update_Idle()
  local GoalEnemyArmyID = ARMY.GetInRangeID(myArmyID, "VISIBLE_CAN_ATTACK_ARMY", 300)
  if table.getn(GoalEnemyArmyID) > 0 then
    Exit_Idle()
    Enter_Pursuit(GoalEnemyArmyID[1])
    return 1
  else
    local GoalTowerID = ARMY.GetInRangeID(myArmyID, "ENEMY_CAPTURED_TOWER", 2000)
    if table.getn(GoalTowerID) > 0 then
      Exit_Idle()
      Enter_Capture(GoalTowerID[1])
      return 1
    end
  end
  return 1
end

function Update_Pursuit()
  if IsThisArmyNotNeedAttack(Pursuit_Goal_ArmyID) then
    Enter_Move1()
    return 1
  end 

  local PursuitKeepTime = TIME.GetGameNowTime() - PursuitStateStartTime
  if PursuitKeepTime >= 2 then
    Enter_Move1()
    return 1
  end  

  MySelfPositionX, MySelfPositionY = ARMY.GetPosition(myArmyID)
  local DistanceFromOrigin = MAP.GetDistanceBetweenTwoPosition(PursuitStateStartPositionX, PursuitStateStartPositionY, MySelfPositionX, MySelfPositionY)
  if DistanceFromOrigin >= 300 then
    Enter_Move1()
    return 1
  end
  return 1
end

function Update_Move1()
  local GoalTowerID = ARMY.GetInRangeID(myArmyID, "ENEMY_CAPTURED_TOWER", 300)
  if table.getn(GoalTowerID) > 0 then
    Enter_Capture(GoalTowerID[1])
  elseif ARMY.IsInGoalRange(myArmyID) then
    Enter_Idle()
  end
  return 1
end

function Update_Capture()
  if ARMY.IsBeenAttacked(myArmyID) then
    local EnemyID = ARMY.GetAttackerID(myArmyID)
    Enter_Pursuit(EnemyID)
  else
    local towerTeam = TOWER.GetOwnerTeam(Capture_Goal_TowerID)
    if towerTeam == ARMY.GetTeam(myArmyID) then 
      Enter_Move1()
    end
  end
  return 1
end

function Update ()
  if STATE == "Idle" then
    Update_Idle()
  elseif STATE == "Pursuit" then
    Update_Pursuit()
  elseif STATE == "Move1" then
    Update_Move1()
  elseif STATE == "Capture" then
    Update_Capture()
  end
  return 1
end
