local function farmhouse_overview(pos)
   local meta = core.get_meta(pos)
   local health = meta:get_int('health')
   local inventory = meta:get_int('inventory')
   local pos1 = vector.add(pos, {x=-3, y=0, z=-3})
   local pos2 = vector.add(pos, {x=3, y=0, z=3})
   local fields = core.find_nodes_in_area(pos1, pos2, 'kobo:farm_field')
   local hp_scale = (health/200) * 3
   local inv_scale = (inventory/250) * 3
   local formspec =
      kobo.building_inv..
      'textarea[3.25,0;7.5,1;;;Farmhouse]'..
      'image[0,0;3,3;kobo_farmhouse_snap.png]'..
      'textarea[3.25,.75;7.5,1;;;Take charge of your own destiny. Gardens are better than grass...\n'..
      'There are '..#fields..' surrounding farm fields.]'..
      'image_button[3.25,2;1,1;kobo_farm_field_ico.png;add_field;;true;false]'..
      'tooltip[add_field;Plant a new field (50 lumber, 100 food);black;white]'..
      'image[0,3.75;'..hp_scale..',.25;kobo_health_fg.png]'..
      'label[0,4.25;Inventory]'..
      'image[0,4.5;3,.25;kobo_graph_bg.png]'..
      'image[0,4.5;'..inv_scale..',.25;kobo_inv_fg.png]'
   return formspec
end

local function farmhouse_overview_wrapper(player, pos)
   local refresh = kobo.refresh[player]
   if refresh then
      core.show_formspec(player, 'kobo:farmhouse', farmhouse_overview(pos))
      core.after(.25, function()
         farmhouse_overview_wrapper(player, pos)
      end)
   end
end

local function farm_field_overview(pos)
   local meta = core.get_meta(pos)
   local health = meta:get_int('health')
   local inventory = meta:get_int('remaining')
   local hp_scale = (health/200) * 3
   local inv_scale = (inventory/250) * 3
   local formspec = kobo.building_inv
   if inventory >= 2 then
      formspec = formspec ..
      'textarea[3.25,0;7.5,1;;;Farmfield]'..
      'image[0,0;3,3;kobo_farm_field_snap.png]'..
      'textarea[3.25,.75;7.5,2.25;;;This certainly tastes better than grass.]'..
      'image[0,3.75;'..hp_scale..',.25;kobo_health_fg.png]'..
      'label[0,4.25;Inventory]'..
      'image[0,4.5;3,.25;kobo_graph_bg.png]'..
      'image[0,4.5;'..inv_scale..',.25;kobo_inv_fg.png]'
   else
      local timer = core.get_node_timer(pos)
      local remaining = math.ceil((timer:get_timeout()- timer:get_elapsed())/60)
      formspec = formspec ..
      'textarea[3.25,0;7.5,1;;;Empty Farmfield]'..
      'image[0,0;3,3;kobo_farm_field_snap.png]'..
      'textarea[3.25,.75;7.5,2.25;;;Crops are growing, about '..remaining..' more minutes before they can be harvested.]'..
      'image[0,3.75;'..hp_scale..',.25;kobo_health_fg.png]'..
      'label[0,4.25;Inventory]'..
      'image[0,4.5;3,.25;kobo_graph_bg.png]'..
      'image[0,4.5;0,.25;kobo_inv_fg.png]'
   end
   return formspec
end

local function farm_field_overview_wrapper(player, pos)
   local refresh = kobo.refresh[player]
   if refresh then
      core.show_formspec(player, 'kobo:farm_field', farm_field_overview(pos))
      core.after(.25, function()
         farm_field_overview_wrapper(player, pos)
      end)
   end
end

local tower_col = {
   type = 'fixed',
   fixed = {{-.4375, -.5, -.4375, .4375, -.3125, .4375}}
   }

local tower_sel = {
   type = 'fixed',
   fixed = {{-.4375, -.5, -.4375, .4375, .25, .4375}}
   }

core.register_node('kobo:farmhouse', {
   description = 'Farmhouse',
   drawtype = 'mesh',
   mesh = 'kobo_farmhouse.obj',
   tiles = {'kobo_farmhouse.png'},
   paramtype = 'light',
   paramtype2 = 'facedir',
   range = 15,
   selection_box = tower_sel,
   collision_box = tower_col,
   groups = {collector = 1, player_building=1},
   _snapshot = 'kobo_farmhouse_snap.png',
   _cost = {150, 200, 25, 100},
   _health = 200,
   _max_inv = 250,
   _material = 'food',
   _long_desc = 'No need for berry bushes when you can have a farm.',
   after_place_node = function(pos, placer)
      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') > 0 then
         local player_name = placer:get_player_name()
         local timer = core.get_node_timer(pos)
         local meta = core.get_meta(pos)
         local resources = kobo.resources[player_name]
         meta:set_string('owner', player_name)
         meta:set_int('inventory', 0)
         meta:set_int('health', 200)
         kobo.place_lights(pos)
         resources.xp = resources.xp + 1
         timer:start(5)
      else
         core.chat_send_player(player_name, 'You can\'t place this here.')
         core.remove_node(pos)
         return true
      end
   end,
   after_destruct = function(pos)
      kobo.remove_lights(pos)
   end,
   on_rightclick = function(pos, node, clicker)
      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
         kobo.player_pos[player_name] = pos
         kobo.refresh[player_name] = true
         farmhouse_overview_wrapper(player_name, pos)
         kobo.save()
      end
   end,
   on_timer = function(pos)
      local timer = core.get_node_timer(pos)
      local meta = core.get_meta(pos)
      local inventory = meta:get_int('inventory')
      if inventory <= 224 then
         local pos1 = vector.add(pos, {x=-3, y=0, z=-3})
         local pos2 = vector.add(pos, {x=3, y=0, z=3})
         local fields = core.find_nodes_in_area(pos1, pos2, 'kobo:farm_field')
         if fields then
            meta:set_int('inventory', inventory + #fields)
            for i = 1, #fields do
               local fields_meta = core.get_meta(fields[i])
               local remaining = fields_meta:get_int('remaining')
               local meta = core.get_meta(pos)
               local inv = meta:get_inventory()
               if remaining == 0 then
                  fields_meta:set_int('remaining', 250)
               elseif remaining <= 1 then
                  core.swap_node(fields[i], {name = 'kobo:farm_field_empty'})
                  local timer = core.get_node_timer(fields[i])
                  timer:start(300)
               else
                  fields_meta:set_int('remaining', remaining - 1)
               end
            end
         end
      end
      timer:start(5)
   end,
})

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

core.register_node('kobo:farm_field', {
   description = 'Farmfield',
   drawtype = 'mesh',
   mesh = 'kobo_farm_field.obj',
   tiles = {'kobo_farm_field.png'},
   use_texture_alpha = 'clip',
   paramtype = 'light',
   paramtype2 = 'facedir',
   groups = {food=1},
   walkable = false,
   selection_box = field_box,
   collision_box = field_box,
   _initial_count = 250,
   after_place_node = function(pos)
      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') > 0 then
         local meta = core.get_meta(pos)
         meta:set_int('remaining', 250)
         meta:set_int('health', 200)
      else
         core.chat_send_player(name, 'You can\'t place that here.')
         core.remove_node(pos)
         return true
      end
   end,
   on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
      local player_name = clicker:get_player_name()
      kobo.player_pos[player_name] = pos
      kobo.refresh[player_name] = true
      farm_field_overview_wrapper(player_name, pos)
   end,
   on_punch = function(pos, node, puncher, pointed_thing)
      local meta = core.get_meta(pos)
      local remaining = meta:get_int('remaining')
      if remaining == 0 then
         if kobo.add_player_inventory_hand(puncher, 'kobo:food') then
            meta:set_int('remaining', 249)
         end
      elseif remaining <= 1 then
         if kobo.add_player_inventory_hand(puncher, 'kobo:food') then
            core.swap_node(pos, {name = 'kobo:farm_field_empty'})
            local timer = core.get_node_timer(pos)
            timer:start(300)
         end
      else
         if kobo.add_player_inventory_hand(puncher, 'kobo:food') then
            meta:set_int('remaining', remaining - 1)
         end
      end
   end,
})

core.register_node('kobo:farm_field_empty', {
   description = 'Empty Farmfield',
   drawtype = 'mesh',
   mesh = 'kobo_farm_field_empty.obj',
   tiles = {'kobo_farm_field.png'},
   paramtype = 'light',
   paramtype2 = 'facedir',
   walkable = false,
   selection_box = field_box,
   collision_box = field_box,
   _initial_count = 0,
   on_construct = function(pos)
      local meta = core.get_meta(pos)
      meta:set_int('remaining', 0)
      meta:set_int('health', 200)
   end,
   on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
      local player_name = clicker:get_player_name()
      kobo.player_pos[player_name] = pos
      kobo.refresh[player_name] = true
      farm_field_overview_wrapper(player_name, pos)
   end,
   on_timer = function(pos)
      local meta = core.get_meta(pos)
      core.swap_node(pos, {name = 'kobo:farm_field'})
      meta:set_int('remaining', 250)
   end,
})

core.register_on_player_receive_fields(function(player, formname, fields)
   if formname == 'kobo:farmhouse' then
      local name = player:get_player_name()
      local pos = kobo.player_pos[name]
      if fields.remove then
         local resources = kobo.resources[name] or {}
         resources.food = resources.food + 113
         resources.lumber = resources.lumber + 150
         resources.metal = resources.metal + 19
         resources.stone = resources.stone + 75
         kobo.refresh[name] = false
         core.remove_node(pos)
         kobo.hud_refresh(player)
         core.close_formspec(name, 'kobo:farmhouse')
      elseif fields.add_field then
         local resources = kobo.resources[name] or {}
         if resources.lumber >= 50 and resources.food >= 100 then
            local pos1 = vector.add(pos, {x=-1, y=0, z=-1})
            local pos2 = vector.add(pos, {x=1, y=0, z=1})
            local open_space = core.find_nodes_in_area(pos1, pos2, 'air')
            if #open_space >= 1 then
               local spot = math.random(1, #open_space)
               core.set_node(open_space[spot], {name = 'kobo:farm_field_empty'})
               local timer = core.get_node_timer(open_space[spot])
               timer:start(300)
               resources.food = resources.food - 100
               resources.lumber = resources.lumber - 50
               kobo.hud_refresh(player)
            else
               pos1 = vector.add(pos, {x=-2, y=0, z=-2})
               pos2 = vector.add(pos, {x=2, y=0, z=2})
               open_space = core.find_nodes_in_area(pos1, pos2, 'air')
               if #open_space >= 1 then
                  local spot = math.random(1, #open_space)
                  core.set_node(open_space[spot], {name = 'kobo:farm_field_empty'})
                  local timer = core.get_node_timer(open_space[spot])
                  timer:start(300)
                  resources.food = resources.food - 100
                  resources.lumber = resources.lumber - 50
                  kobo.hud_refresh(player)
               end
            end
         else
            core.chat_send_player(name, 'You need more resources.')
         end
      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.')
      end
   elseif formname == 'kobo:farm_field' then
      local name = player:get_player_name()
      local pos = kobo.player_pos[name]
      if fields.remove then
         core.remove_node(pos)
         kobo.refresh[name] = false
         core.close_formspec(name, 'kobo:farm_field')
      elseif fields.repair then
         core.chat_send_player(name, 'You can\'t repair this.')
      end
   end
end)
