local function base_overview(pos)
   local meta = core.get_meta(pos)
   local health = meta:get_int('health')
   local scale = (health/500) * 3

   local formspec =
      kobo.building_inv..
      'textarea[3.25,0;7.5,1;;;Town Center]'..
      'image[0,0;3,3;kobo_base_snap.png]'..
      'image_button[3.25,2;1,1;kobo_lumberjack_ico.png;lumberjack;;true;false]'..
      'tooltip[lumberjack;Create a lumberjack (25 lumber, 25 food);black;white]'..
      'image_button[4.5,2;1,1;kobo_forager_ico.png;forager;;true;false]'..
      'tooltip[forager;Create a forager (5 lumber, 25 food);black;white]'..
      'image_button[5.75,2;1,1;kobo_miner_ico.png;miner;;true;false]'..
      'tooltip[miner;Create a miner (15 lumber, 15 stone, 50 food);black;white]'..
      'image_button[7,2;1,1;kobo_courier_ico.png;courier;;true;false]'..
      'tooltip[courier;Create a courier (15 lumber, 5 metal, 50 food);black;white]'..
      'image_button[8.25,2;1,1;kobo_repairman_ico.png;repairman;;true;false]'..
      'tooltip[repairman;Create a repairman (15 lumber, 15 metal, 25 food);black;white]'..
      'image[0,3.75;'..scale..',.25;kobo_health_fg.png]'

   return formspec
end

local function base_overview_wrapper(player, pos)
   local refresh = kobo.refresh[player]
   if refresh then
      core.show_formspec(player, 'kobo:base', base_overview(pos))
      core.after(.25, function()
         base_overview_wrapper(player, pos)
      end)
   end
end

local function base(player)
   local formspec =
      kobo.building_inv..
      'textarea[3.25,0;7.5,1;;;'..player..'\'s Town Center]'..
      'image[0,0;3,3;kobo_base_snap.png]'
   return formspec
end

local function game_over()
   local resources = kobo.goblins
   local formspec =
   'formspec_version[7]'..
   'size[12,8]'..
   'background[-1,-1;14,10;kobo_defeat_screen.png]'..
   'style_type[textarea;textcolor=black;font_size=+10]'..
   'textarea[0,.125;12,8;;;   Aww, too bad, you lose. The goal is to NOT let the goblins destroy your base, maybe that wasn\'t made clear in the instructions. If so my apologies.\n'..
   'You survived '..resources.wave..' waves of goblins, doubtless you\'ll do better next time.]'
   return formspec
end

local base_col = {
   type = 'fixed',
   fixed = {{-.5, -.5, -.5, 1.5, -.4375, 1.5}}
   }

local base_sel = {
   type = 'fixed',
   fixed = {{-.5, -.5, -.5, 1.5, -.4375, 1.5},
            {.5, -.5, .5, 1.5, 1, 1.5}}
   }

core.register_node('kobo:base', {
   description = 'Town Center',
   drawtype = 'mesh',
   mesh = 'kobo_base.obj',
   tiles = {'kobo_base.png'},
   paramtype = 'light',
   paramtype2 = 'facedir',
   range = 15,
   selection_box = base_sel,
   collision_box = base_col,
   groups = {storage=1, player_building=1},
   _snapshot = 'kobo_base_snap.png',
   _cost = {1000, 1000, 1000, 1000},
   _health = 500,
   _max_inv = 'No Max',
   _long_desc = 'Your central storage building. You can create villagers here, and they will drop off resources here.',
   after_place_node = function(pos, placer, itemstack)
      local player_name = placer:get_player_name()
      if kobo.space_for_building(pos) then
         local pos_check = vector.subtract(pos, {x=0, y=1, z=0})
         local node_check = core.get_node(pos_check)
         if core.get_item_group(node_check.name, 'ground') > 1 then
            local meta = core.get_meta(pos)
            meta:set_string('owner', player_name)
            meta:set_string('infotext', player_name..'\'s base')
            meta:set_int('health', 500)
            kobo.place_lights(pos)
            kobo.bases[player_name] = core.pos_to_string(pos)
         else
            core.chat_send_player(player_name, 'Place your base on grassy ground.')
            core.remove_node(pos)
            return true
         end
      else
         core.chat_send_player(player_name, 'There is something in the way.')
         core.remove_node(pos)
         return itemstack
      end
   end,
   on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
      local player_name = clicker:get_player_name()
      local meta = core.get_meta(pos)
      local owner = meta:get_string('owner')
      if owner == player_name or core.check_player_privs(clicker, {server = true}) then
         local player_inv = clicker:get_inventory()
         local items = player_inv:get_stack('hand', 1)
         local item_name = items:get_name()
         local item_count = items:get_count()
         local resources = kobo.resources[player_name] or {}
         if item_name == 'kobo:lumber' then
            resources.lumber = resources.lumber + item_count
         elseif item_name == 'kobo:stone' then
            resources.stone = resources.stone + item_count
         elseif item_name == 'kobo:food' then
            resources.food = resources.food + item_count
         elseif item_name == 'kobo:metal' then
            resources.metal = resources.metal + item_count
         end
         player_inv:set_list('hand', {})
         kobo.refresh[player_name] = true
         base_overview_wrapper(player_name, pos)
         kobo.hud_refresh(clicker)
         kobo.player_pos[player_name] = pos
         kobo.save()
      else
         core.show_formspec(player_name, 'kobo:base', base(player_name))
      end
   end,
   on_destruct = function(pos)
      local meta = core.get_meta(pos)
      local owner = meta:get_string('owner')
      core.show_formspec(owner, 'kobo:game_over', game_over())
   end,
   after_destruct = function(pos, oldnode)
      kobo.remove_lights(pos)
      kobo.remove_building_spaces(pos, oldnode)
   end,
})

core.register_on_player_receive_fields(function(player, formname, fields)
   local name = player:get_player_name()
   if fields.quit then
      kobo.refresh[name] = false
   end
   if formname == 'kobo:base' then
      if fields.lumberjack then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 25 and resources.food >= 25 then
            local pos = kobo.player_pos[name]
            local home_pos = vector.add(pos, {x=0, y=1, z=0})
            local lumberjack = minetest.add_entity(pos, 'kobo:lumberjack')
            local lumberjack_entity = lumberjack:get_luaentity()
            lumberjack_entity.owner = name
            lumberjack_entity.home = home_pos
            lumberjack_entity.state = 'idle'
            lumberjack_entity.inv = 0
            resources.lumber = resources.lumber - 25
            resources.food = resources.food - 25
            kobo.hud_refresh(player)
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      elseif fields.forager then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 25 and resources.food >= 25 then
            local pos = kobo.player_pos[name]
            local home_pos = vector.add(pos, {x=0, y=1, z=0})
            local forager = minetest.add_entity(pos, 'kobo:forager')
            local forager_entity = forager:get_luaentity()
            forager_entity.owner = name
            forager_entity.home = home_pos
            forager_entity.state = 'idle'
            forager_entity.inv = 0
            resources.lumber = resources.lumber - 5
            resources.food = resources.food - 25
            kobo.hud_refresh(player)
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      elseif fields.miner then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 15 and resources.food >= 50 and resources.stone >= 15 then
            local pos = kobo.player_pos[name]
            local home_pos = vector.add(pos, {x=0, y=1, z=0})
            local miner = minetest.add_entity(pos, 'kobo:miner')
            local miner_entity = miner:get_luaentity()
            miner_entity.owner = name
            miner_entity.home = home_pos
            miner_entity.state = 'idle'
            miner_entity.inv = 0
            miner_entity.mat = ''
            resources.lumber = resources.lumber - 15
            resources.food = resources.food - 50
            resources.stone = resources.stone - 15
            kobo.hud_refresh(player)
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      elseif fields.courier then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 15 and resources.food >= 50 and resources.metal >= 5 then
            local pos = kobo.player_pos[name]
            local home_pos = vector.add(pos, {x=0, y=1, z=0})
            local courier = minetest.add_entity(pos, 'kobo:courier')
            local courier_entity = courier:get_luaentity()
            courier_entity.owner = name
            courier_entity.home = home_pos
            courier_entity.state = 'idle'
            courier_entity.inv = 0
            courier_entity.mat = ''
            resources.lumber = resources.lumber - 15
            resources.food = resources.food - 50
            resources.metal = resources.metal - 5
            kobo.hud_refresh(player)
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      elseif fields.repairman then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 15 and resources.food >= 25 and resources.metal >= 15 then
            local pos = kobo.player_pos[name]
            local home_pos = vector.add(pos, {x=0, y=1, z=0})
            local repairman = minetest.add_entity(pos, 'kobo:repairman')
            local repairman_entity = repairman:get_luaentity()
            repairman_entity.owner = name
            repairman_entity.home = home_pos
            repairman_entity.state = 'idle'
            resources.lumber = resources.lumber - 15
            resources.food = resources.food - 25
            resources.metal = resources.metal - 15
            kobo.hud_refresh(player)
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      elseif fields.remove then
         local pos = kobo.player_pos[name]
--         core.remove_node(pos)
         core.chat_send_player(name, 'You can\'t do that right now.')
         kobo.refresh[name] = false
         core.close_formspec(name, 'kobo:base')
      elseif fields.repair then
         local pos = kobo.player_pos[name]
         local new_pos = vector.add(pos, {x=0, y=1, z=0})
         core.set_node(new_pos, {name='kobo:repair'})
         core.chat_send_player(name, 'Summonend a repairman.')
      elseif fields.quit then
         kobo.refresh[name] = false
      end
   end
end)
