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

function Init ()
  startEscapingRange = 1100
  
  fMinEscapeRange = 500
  fMaxEscapeRange = 800
  fAngle = 90
  
  Enter_Escape()
end


--------------------------------------------------------------------------------------
---------------------------------- start Escape state --------------------------------
--------------------------------------------------------------------------------------

function Enter_Escape ()
  STATE = "Escape"
  ARMY.SetBehavior(myArmyID, "WalkTo")
  
  fNextDecideEscapeTime = TIME.GetGameNowTime()
  fNextDecideEscapePosTime = TIME.GetGameNowTime()
  fEscapePosX, fEscapePosY = ARMY.GetPosition(myArmyID)
  ARMY.SetGoalPosition(myArmyID, fEscapePosX, fEscapePosY)
  fAtPosAccuracyRange = 200
end

function Update_Escape ()
  local iNearestEnemyArmyID = ARMY.GetInRangeID(myArmyID, "VISIBLE_CAN_ATTACK_ARMY", 100000)
  local fCurEnemyPosX, fCurEnemyPosY = ARMY.GetPosition(iNearestEnemyArmyID)
  local fCurPosX, fCurPosY = ARMY.GetPosition(myArmyID)
  
  local fDistanceEnemyAndThisArmy = MAP.GetDistanceBetweenTwoPosition(fCurPosX, fCurPosY, fCurEnemyPosX, fCurEnemyPosY)
  
  if fDistanceEnemyAndThisArmy < startEscapingRange then  
  
    -- check if need to redecide escape position
    local fCurTime = TIME.GetGameNowTime()
    local bNeedToDecideEscapePosAgain = false
    if fCurTime >= fNextDecideEscapeTime then
      bNeedToDecideEscapePosAgain = true
    else
      local fDistanceFromEscapePos = MAP.GetDistanceBetweenTwoPosition(fCurPosX, fCurPosY, fEscapePosX, fEscapePosY)
      if fDistanceFromEscapePos < fAtPosAccuracyRange then
        --already at the position, so need to re-decide
        bNeedToDecideEscapePosAgain = true
      end
    end
  
    if bNeedToDecideEscapePosAgain then
      -- set new escape position
      local fEscapingDirX, fEscapingDirY = fCurPosX-fCurEnemyPosX, fCurPosY-fCurEnemyPosY
      fEscapePosX, fEscapePosY = MAP.GetRandomPositionWithCondition(fCurPosX, fCurPosY, fEscapingDirX, fEscapingDirY, fMinEscapeRange, fMaxEscapeRange, fAngle)
      ARMY.SetGoalPosition(myArmyID, fEscapePosX, fEscapePosY)
      local decideEscapeWaitTime = math.random(500,1000) / 1000.0
      fNextDecideEscapeTime = fCurTime + decideEscapeWaitTime
    end  
  
  end
  
end

function Exit_Escape()
end

--------------------------------------------------------------------------------------
----------------------------------- end Escape state ---------------------------------
--------------------------------------------------------------------------------------

function Update ()
  if STATE == "Escape" then
    Update_Escape()
  end
end
