include("../scripts/ai/include/basic.lua")

-- Required control rate
control_rate = 2

-- Required "control" function.
function control()
 task = ai.taskname()

 enemy = ai.getenemy()
 if task ~= "attack" and enemy ~= nil then
   ai.hostile(enemy)
   ai.pushtask(0, "attack", enemy)

 -- Enter hyperspace if possible.
 elseif task == "hyperspace" then
   ai.hyperspace() -- Try to hyperspace.

 -- Get new task.
 elseif task == "none" then
  planet = ai.landplanet()
  -- Planet needs to exist..
  if planet == nil then
   ai.pushtask(0, "hyperspace")
  else
   ai.pushtask(0, "go", planet)
  end
 end
end

function attacked(attacker)
 task = ai.taskname()
 if task ~= "attack" and task ~= "runaway" then
  taunt(attacker)

  ai.pushtask(0, "attack", attacker)
 elseif task == "attack" then
  if ai.targetid() ~= attacker then
   ai.pushtask(0, "attack", attacker)
  end
 end
end

function create()
 if rnd.int(0,2)==0 then -- More money, but less often.
  ai.setcredits(rnd.int(1000, ai.shipprice()/70))
 end
 if rnd.int(0,2)==0 then
  ai.broadcast("The Empire is watching")
 end
end

function taunt(target)
  taunts = {
    "How dare you attack me!?",
    "You can not defeat the Empire!",
    "You will hang for this!",
    "DIE!!"
  }
  ai.comm(target, taunts[rnd.int(1, #taunts)])
end

function go()
 target = ai.target()
 dir = ai.face(target)
 dist = ai.dist(target)
 bdist = ai.minbrakedist()
 if dir < 10 and dist > bdist then
  ai.accel()
 elseif dir < 10 and dist < bdist then
  ai.poptask()
  ai.pushtask(0, "stop")
 end
end

function stop()
 if ai.isstopped() then
  ai.stop()
  ai.poptask()
  ai.settimer(0, rnd.int(8000, 15000))
  ai.pushtask(0, "land")
 else
  ai.brake()
 end
end

function land()
 if ai.timeup(0) then
  ai.pushtask(0, "hyperspace")
 end
end

