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

function Init ()
--WANDER.AddGoalPoint(myArmyID, 1000, 1000, 0)
--WANDER.AddGoalPoint(myArmyID, 1000, -1000, 0)
--WANDER.AddGoalPoint(myArmyID, -1000, -1000, 0)
--WANDER.AddGoalPoint(myArmyID, -1000, 1000, 0)
  Enter_Wander()
end

function Enter_Wander ()
  ARMY.SetBehavior(myArmyID, "Wander")
  STATE = "Wander"
end

function Enter_Chase (EnemyID)
  Chase_Start_PositionX, Chase_Start_PositionY = ARMY.GetPosition(myArmyID)
  Chase_Start_Time = TIME.GetGameNowTime()
  Chase_Goal_Army = EnemyID

  ARMY.SetBehavior(myArmyID, "AttackLord")
  ARMY.SetGoal(myArmyID, "ARMY", Chase_Goal_Army)
  STATE = "Chase"
end

function Enter_Move ()
  ARMY.SetBehavior(myArmyID, "WalkTo")
  ARMY.SetGoalPosition(myArmyID, Wander_Exit_PositionX, Wander_Exit_PositionY)
  STATE = "Move"
end

function Enter_Flee (EscapeEnemyID)
  Flee_From_Army = EscapeEnemyID
  ARMY.SetBehavior(myArmyID, "Escape")
  STATE = "Flee"
end

function Exit_Wander ()
  Wander_Exit_PositionX, Wander_Exit_PositionY = ARMY.GetPosition(myArmyID)
end

function Update_Wander ()
  local ArmyID = ARMY.GetInRangeID(myArmyID, "VISIBLE_CAN_ATTACK_ARMY", 1000)
  if table.getn(ArmyID) > 0 then
    Exit_Wander()
    Enter_Chase(ArmyID[1])
    return 1
  end
end

function Update_Chase ()
  if IsThisArmyNotNeedAttack(Chase_Goal_Army) then
    Enter_Move()
    return 1
  elseif ARMY.GetHPPercent(myArmyID) < 0.2 then
    local EnemyID = ARMY.GetAttackerID(myArmyID)
    Enter_Flee(EnemyID)
    return 1
  else
    local TimeDif = TIME.GetGameNowTime() - Chase_Start_Time
    if TimeDif > 3 then
      Enter_Move()
      return 1
    else
      local Now_PositionX, Now_PositionY = ARMY.GetPosition(myArmyID)
      local DistanceFromOrigin = MAP.GetDistanceBetweenTwoPosition(Now_PositionX, Now_PositionY, Chase_Start_PositionX, Chase_Start_PositionY)
      if DistanceFromOrigin > 500 then
        Enter_Move()
        return 1
      end
    end
  end
end

function Update_Move ()
  if ARMY.IsBeenAttacked(myArmyID) then
    local EnemyID = ARMY.GetAttackerID(myArmyID)
    Enter_Chase(EnemyID)
    return 1
  elseif ARMY.IsInGoalRange(myArmyID) then
    Enter_Wander()
    return 1
  end  
end

function Update_Flee ()
  local FleeGoalPositionX, FleeGoalPositionX = ARMY.GetPosition(Flee_From_Army)
  local Now_PositionX, Now_PositionY = ARMY.GetPosition(myArmyID)
  local DiffDistance = MAP.GetDistanceBetweenTwoPosition(FleeGoalPositionX, FleeGoalPositionX, Now_PositionX, Now_PositionY)
  if DiffDistance > 300 then
    Enter_Move()
    return 1
  end
end

function Update ()
  if STATE == "Wander" then
    Update_Wander()
  elseif STATE == "Chase" then
    Update_Chase()
  elseif STATE == "Move" then
    Update_Move()
  elseif STATE == "Flee" then
    Update_Flee()
  end
end
