NPC = Actor:createSubClass();
registerSpawn("NPC");

function NPC:init()

   Actor.init(self);

   if not self.editorProperties then
      self.editorProperties = {};
   end

   self.editorProperties.goalNode = "";

   self.moveSpeed = 4;
   self.jumpPower = 24;
   self.jumpForward = 6;

   self:setSize(32, 48);

   self:setGravityInfluence(1);
   self:setBlockable(true);

end

function NPC:gotoGoalBehavior()

   local goalEnt = entitiesByName[self.editorProperties.goalNode];

   local x, y = self:getPos();
   local dx, dy = self:getVel();
   local w, h = self:getSize();
   local gx = x;
   local gy = y;

   local shouldJump = false;

   if goalEnt and self:getOnGround() then

      gx, gy = goalEnt:getPos();

      if math.abs(gx - x) > 32 then

         if gx < x then
            dx = self.moveSpeed * -1;
         end

         if gx > x then
            dx = self.moveSpeed;
         end

      end

   end

   local dxSign = 0;
   if not (dx == 0) then
      dxSign = (dx / math.abs(dx));
   end

   if self:getOnGround() then

      if not getBoxTouchesWorld(3,
                                x + dxSign * w, y - h, 
                                x + dxSign * w + 1, y - h + 1) then

         -- Gap in the ground in front of us.
         if gy <= y - (h / 2) then
            -- Target is below us. Just drop.
         else
            -- Jump over the gap.
            shouldJump = true;
         end

      end

      if getBoxTouchesWorld(3,
                            x + dxSign * w, y, 
                            x + dxSign * w + 1, y + 1) then

         -- Obstruction right in front of us.
         shouldJump = true;

      end

      if math.abs(gx - x) < 32 and gy - y > 16 then
         -- Target is above us.
         shouldJump = true;
      end

   end

   if shouldJump then

      dy = self.jumpPower;
      dx = self.jumpForward * dxSign;

   end

   self:setVel(dx, dy);

end

function NPC:update()

   -- TODO: Remove this.
   local linkTarget = self:getLinkTarget();
   self:setLinkTarget("");
   linkTarget = entitiesByName[linkTarget];
   if linkTarget then
      self.editorProperties.goalNode = linkTarget:getName();
   end
   
   self:gotoGoalBehavior();

end

function NPC:collided(otherEnt)

   local ent = entitiesByName[otherEnt];
   
   if ent then

      if ent.isPathNode and otherEnt == self.editorProperties.goalNode then

         local nextTargetList = ent:getAllLinkTargets();

         local targetNum = math.random(#nextTargetList);

         self.editorProperties.goalNode = nextTargetList[targetNum];

         writeConsole(self:getName().." now seeking "..self.editorProperties.goalNode.."\n");


      end

   end

end


