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 ~= 0 then
   ai.hostile(enemy)
  ai.pushtask(0, "attack", enemy)
 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)
 num = rnd.int(0,4)
 if num == 0 then msg = "How dare you attack me!?"
 elseif num == 1 then msg = "You can not defeat the Empire!"
 elseif num == 2 then msg = "You will hang for this!"
 elseif num == 3 then msg = "DIE!"
 end
 if msg then ai.comm(attacker, msg) end
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

function hyperspace()
 dir = ai.face(-1) -- Face away from (0,0)
 if(dir < 10) then
  ai.accel()
 end
end