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

--Required control rate.
control_rate = 2

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

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

  -- Running pilot has healed up some.
  elseif task == "runaway" then
    if ai.parmour() == 100 then
      -- "attack" should be called after "runaway".
      ai.poptask()
  elseif ai.dist(ai.pos(ai.targetid())) > 300 then
   ai.hyperspace()
  end

  -- Hurt pilot wants to run away.
  elseif task == "attack" then
    if ai.parmour() < 80 then
      ai.pushtask(0, "runaway", ai.targetid())
    end

    -- Nothing to do.
  elseif task ~= "attack" and task ~= "runaway" then
    -- If getenemy() is 0, there is no enemy around.
    enemy = ai.getenemy()
    if ai.parmour() == 100 and enemy ~= 0 then
      -- Taunts.
      num = rnd.int(0,5)
      if num == 0 then msg = "Prepare to be boarded!"
      elseif num == 1 then msg = "Whoa! Lookie what we found here!"
      elseif num == 2 then msg = "What's a ship like you doing in a place like this?"
      end
      ai.comm(enemy,msg)

      -- Make hostile to the enemy (mainly, player! YOU!).
      ai.hostile(enemy)

      -- Go ahead and attack.
      ai.combat() -- Set to be in combat.
      ai.pushtask(0, "attack", enemy) -- Begin the attack.
    -- Nothing to attack.
    else
      ai.pushtask(0, "hyperspace")
    end
  end
end

-- Required "attacked" function
function attacked(attacker)
  task = ai.taskname()

  -- Pirate isn't fighting or fleeing already.
  if task ~= "attack" and task ~= "runaway" then
    taunt(attacker)
    ai.pushtask(0, "attack", attacker)
  -- Pirate is fighting bit switches to new target (doesn't forget the old on though).
  elseif task == "attack" then
    if ai.targetid() ~= attacker then
      ai.pushtask(0, "attack", attacker)
    end
  end
end

function create()
 if rnd.int(0,5) ~= 0 then
  ai.setcredits(0, ai.shipprice()/100)
 end
end

function taunt(target)
  -- Some taunts.
  taunts = {
    "How dare you attack me?!",
    "Aha! You think you can best me!?",
    "JUST! DIE!",
    "Ohh, I'm going to enjoy this!"
  }
  ai.comm(target, taunts[rnd.int(1, #taunts)])
end

-- Fly to the player. Pointless until hyperspace is implemented.
function fly()
  target = player
  dir = ai.face(target)
  dist = ai.dist(ai.pos(target))
  if dir < 10 and dist > 300 then
    ai.accel()
  end
end

