ls_player = {}

local modpath = core.get_modpath('ls_player')
dofile(modpath..'/bones.lua')
dofile(modpath..'/formspecs.lua')
dofile(modpath..'/help.lua')

core.register_item(":", {
   type = "none",
   wield_image = "wieldhand.png",
   wield_scale = {x=1,y=1,z=2.5},
   tool_capabilities = {
      full_punch_interval = 0.9,
      max_drop_level = 0,
      groupcaps = {
         breakable = {times={[1]=1.0,[2]=0.75,[3]=0.5,[4]=0.25}, uses=0},
      },
      damage_groups = {fleshy=1},
   }
})

local function player_update()
   local tod = core.get_timeofday()
   local ratio = core.time_to_day_night_ratio(tod)
   if tod > .217 and tod < .782 then
      ratio = .4
   end
   for _, player in pairs(core.get_connected_players()) do
      local hp = player:get_hp()
      if hp > 0 and hp < 20 then
         player:set_hp(hp + 1)
      end
      player:override_day_night_ratio(ratio)
      --player:override_day_night_ratio(1)
   end
   core.after(30.0, player_update)
end

core.register_on_joinplayer(function(player)
   player:set_sky({
      type = 'regular',
      sky_color = {
         day_sky = '#003b70',
         day_horizon = '#004765',
         dawn_sky = '#3e487e',
         dawn_horizon = '#263156'
      }
   })
   player_update()
   local name = player:get_player_name()
   player:set_inventory_formspec(ls_player.inv)
end)

core.after(5.0, player_update)

core.register_on_newplayer(function(player)
   local player_inv = player:get_inventory()
   local name = player:get_player_name()
   player_inv:add_item('main', 'ls_crystal:torch_1 20')
   player_inv:add_item('main', 'ls_crystal:long_range 2')
   player_inv:add_item('main', 'ls_stations:workbench 2')
   player_inv:add_item('main', 'ls_nodes:bed')
   core.show_formspec(name, 'ls_player:help', ls_player.help_form)
end)

core.register_on_dieplayer(function(player)
   local player_name = player:get_player_name()
   local pos = vector.round(player:get_pos())
   local player_inv = player:get_inventory()
   core.set_node(pos, {name = 'ls_player:bones'})
   local meta = core.get_meta(pos)
   local inv = meta:get_inventory()
   inv:set_size('main', 32)
   for i = 1, player_inv:get_size('main') do
      local stack = player_inv:get_stack('main', i)
      inv:add_item('main', stack)
   end
   player_inv:set_list('main', {})
end)

core.register_on_respawnplayer(function(player)
   local name = player:get_player_name()
   local pos = ls_crystal.data[name].spawn
   if pos then
      player:set_pos(pos)
      return true
   end
end)
