local function goblin_debug(obj)
   local formspec =
   'formspec_version[7]'..
   'size[12,8]'..
   'background[-1,-1;14,10;lobby_button_bg.png]'..
   'label[3,1;Goblin state: '..obj.state..'.]'..
   'label[3,2;Goblin health: '..obj.health..'.]'..
   'label[3,1.5;Goblin inventory: '..obj.inv..'.]'..
   'button_exit[6,4;4,1;exit;Exit]'
   return formspec
end

core.register_entity('kobo:goblin_scout', {
   initial_properties = {
      visual = 'mesh',
      mesh = 'kobo_goblin.obj',
      visual_size = {x=10, y=10},
      physical = true,
      collide_with_objects = false,
      collisionbox = {-.125, -.5, -.125, .125, -.125, .125},
      textures = {'kobo_goblin_scout.png'},
      automatic_face_movement_dir = 0.0,
   },

   on_activate = function(self, staticdata, dtime_s)
      local data = core.deserialize(staticdata)
      if data then
         self.node_timer = data.node_timer
         self.state = data.state
         self.path = data.path
         self.step = data.step
         self.inv = data.inv
         self.last_job = data.last_job
         self.home = data.home
         self.health = data.health
         self.wander_count = data.wander_count
      else
         self.last_job = self.object:get_pos()
         self.state = 'idle'
         self.step = 0
         self.health = 25
         self.wander_count = 0
      end
      local clean_dir
      local resources = kobo.goblins
      print (dump(resources))
      if resources.nearest_base.x then
         local dir = vector.direction(self.object:get_pos(), resources.nearest_base)
         clean_dir = vector.multiply(dir, {x=1, y=0, z=1})
      else
         local dir = vector.random_direction()
         clean_dir = vector.multiply(dir, {x=1, y=0, z=1})
      end
      self.object:set_velocity(clean_dir)
      self.last_job = self.object:get_pos()
      self.state = 'wandering'
   end,

   get_staticdata = function(self)
      local data ={}
      data.node_timer = self.node_timer
      data.state = self.state
      data.path = self.path
      data.step = self.step
      data.inv = self.inv
      data.last_job = self.last_job
      data.home = self.home
      data.health = self.health
      data.wander_count = self.wander_count
      return core.serialize(data)
   end,

   on_step = function(self, dtime, moveresults)
      self.node_timer = (self.node_timer or 0) + dtime
      if self.node_timer > 1 then
         self.node_timer = 0
         if self.state == 'idle' then --Find a building to ravage
            local self_pos = vector.add(self.object:get_pos(), {x=0, y=1, z=0})
            local pos1 = vector.add(self_pos, {x=-10, y=-1, z=-10})
            local pos2 = vector.add(self_pos, {x=10, y=0, z=10})
            local player_buildings = core.find_nodes_in_area(pos1, pos2, 'group:player_building')
            if #player_buildings >= 1 then
               local selection = math.random(1, #player_buildings)
               local path = core.find_path(self_pos, vector.add(player_buildings[selection], {x=0, y=1, z=0}), 5, 1, 1)
               if path then
                  self.path = path
                  self.step = 2
                  self.state = 'traveling'
               else --Make the unit wander around for a while.
                  self.state = 'idle'
               end
            else
               local metal = core.find_node_near(self_pos, 20, 'kobo:metal_mine_2')
               if metal then
                  local mining_spot = core.find_node_near(metal, 1, 'kobo:metal_mine_2', true)
                  local path = core.find_path(self_pos, vector.add(mining_spot, {x=0, y=1, z=0}), 5, 1, 1)
                  if path then
                     self.path = path
                     self.step = 2
                     self.state = 'traveling'
                  else --Make the unit wander around for a while.
                     self.state = 'idle'
                  end
               else
                  local dir = vector.random_direction()
                  local clean_dir = vector.multiply(dir, {x=1, y=0, z=1})
                  self.object:set_velocity(clean_dir)
                  self.state = 'wandering'
                  self.last_job = self_pos
               end
            end
         elseif self.state == 'traveling' then
            if #self.path > (self.step - 1) then
               local pos = self.object:get_pos()
               local perhaps = vector.direction(pos, self.path[self.step])
               self.object:set_velocity({x = perhaps.x, y = 0, z = perhaps.z})
               self.step = self.step + 1
            else
               local self_pos = vector.round(self.object:get_pos())
               local building = core.find_node_near(self_pos, 1, 'group:player_building', true)
               local metal = core.find_node_near(self_pos, 1, 'kobo:metal_mine_2', true)
               local base = core.find_node_near(self_pos, 1, 'kobo:goblin_base', true)
               if building then
                  self.object:set_velocity({x=0, y=0, z=0})
                  self.state = 'working'
                  self.last_job = building
               elseif metal then
                  self.object:set_velocity({x=0, y=0, z=0})
                  self.state = 'working'
                  self.last_job = metal
               elseif base then
                  self.object:set_velocity({x=0, y=0, z=0})
                  self.state = 'idle'
                  self.inv = 0
               end
            end
         elseif self.state == 'working' then
            self.wander_count = 0
            local pos = self.last_job
            local meta = core.get_meta(pos)
            local node = core.get_node(pos)
            if node.name == 'kobo:base' then
               local player_name = meta:get_string('owner')
               if player_name ~= '' then -- Must be a player's building
                  local player = core.get_player_by_name(player_name)
                  local player_resources = kobo.resources[player_name] or {}
                  local goblin_resources = kobo.goblins
                  goblin_resources.nearest_base = pos
                  if player_resources.metal >= 1 then
                     player_resources.metal = player_resources.metal - 1
                     goblin_resources.metal = goblin_resources.metal + 1
                  elseif player_resources.food >= 1 then
                     player_resources.food = player_resources.food - 1
                     goblin_resources.food = goblin_resources.food + 1
                  elseif resources.lumber >= 1 then
                     player_resources.lumber = player_resources.lumber - 1
                     goblin_resources.lumber = goblin_resources.lumber + 1
                  end
                  kobo.hud_refresh(player)
               end
            elseif node.name == 'kobo:metal_mine_2' then
               local inventory_count = self.inv or 30
               if inventory_count < 25 then
                  self.inv = self.inv + 1
                  local remaining = meta:get_int('remaining')
                  if remaining == 0 then
                     local def = minetest.registered_nodes[node.name]
                     remaining = def._initial_count
                     if remaining then
                        meta:set_int('remaining', remaining - 1)
                     end
                  elseif remaining == 1 then
                     core.remove_node(pos)
                     self.state = 'idle'
                  else
                     meta:set_int('remaining', remaining - 1)
                  end
                  local goblin_resources = kobo.goblins
                  goblin_resources.metal = goblin_resources.metal + 1
               else
                  local self_pos = vector.add(self.object:get_pos(), {x=0, y=1, z=0})
                  local path = core.find_path(self_pos, self.home, 5, 1, 1)
                  if path then
                     self.path = path
                     self.step = 2
                     self.state = 'traveling'
                  else --Make the unit wander around for a while.
                     self.state = 'idle'
                  end
               end
            else --Player node with inventory
               local pos = self.last_job
               local meta = core.get_meta(pos)
               local inventory = meta:get_int('inventory')
               if inventory > 2 then
                  local inventory_count = self.inv
                  if inventory_count < 25 then
                     self.inv = self.inv + 1
                     meta:set_int('inventory', inventory - 1)
                     local goblin_resources = kobo.goblins
                     goblin_resources.lumber = goblin_resources.lumber + 1
                  else
                     local self_pos = vector.add(self.object:get_pos(), {x=0, y=1, z=0})
                     local path = core.find_path(self_pos, self.home, 5, 1, 1)
                     if path then
                        self.path = path
                        self.step = 2
                        self.state = 'traveling'
                     else --Make the unit wander around for a while.
                        self.state = 'idle'
                     end
                  end
               else
                  self.state = 'idle'
               end
            end
         elseif self.state == 'wandering' then
            self.wander_count = self.wander_count or 1
            self.step = self.step + 1
            if self.step > 20 then
               self.state = 'idle'
               self.step = 0
               self.wander_count = self.wander_count + 1
            end
            local self_pos = self.object:get_pos()
            if self.last_job then
               if vector.distance(self.last_job, self_pos) < .25 then
                  self.state = 'idle'
               end
            else
               self.object:remove()
            end
            if self.wander_count > 20 then
               self.object:remove()
            end
         end
      end
   end,

   on_punch = function(self, puncher)
      self.health = self.health - 1 or 24
      if self.health <= 0 then
         self.object:remove()
      end
   end,

   on_deactivate = function(self, removal)
      if removal then
         local pos = self.object:get_pos()
         local tombstone = minetest.add_entity(pos, 'kobo:goblin_tombstone')
         local tombstone_entity = tombstone:get_luaentity()
         tombstone_entity.node_timer = 0
      end
   end,

   on_rightclick = function(self, clicker)
      if core.check_player_privs(clicker, {server = true}) then
         local player_name = clicker:get_player_name()
         core.show_formspec(player_name, 'kobo:goblin_debug', goblin_debug(self))
      end
   end,

})
