PyuTest.deal_damage = function(target, damage, reason)
  local hp = target:get_hp()

  if hp > 0 then
    target:set_hp(hp - damage, reason)
  end
end

PyuTest.DAMAGE_TYPES = {
  explosion = function(range)
    return {
      type = "set_hp",
      _pyutest = {
        type = "explosion",
        range = range
      }
    }
  end,
  burning = function ()
    return {
      type = "set_hp",
      _pyutest = {
        type = "burning"
      }
    }
  end
}

PyuTest.mt_damage_to_pyutest_damage = function(reason)
  return reason._pyutest or reason
end

core.register_on_dieplayer(function(player, reason)
    local playername = player:get_player_name()

    local message = string.format("%s died", playername)
    if reason.type == "fall" then
      message = string.format("%s fell from a high place", playername)
    elseif reason.type == "drown" then
      message = string.format("%s drowned", playername)
    elseif reason.type == "respawn" then
      return
    elseif reason.type == "punch" then
      local entity = reason.object:get_luaentity()
      if entity ~= nil then
        local name = reason.object:get_properties().nametag or entity.name or "an unnamed monster!"
        message = string.format("%s was slain by %s", playername, name)
      else
        local name = reason.object:get_player_name()
        local itemname = reason.object:get_wielded_item():get_short_description()
        message = string.format("%s was slain by %s using %s", playername, name, itemname)
      end
    elseif reason.type == "set_hp" then
      local newreason = PyuTest.mt_damage_to_pyutest_damage(reason)

      if newreason.type == "explosion" then
        message = string.format("%s blew up", playername)
      elseif newreason.type == "burning" then
        message = string.format("%s burned to death", playername)
      end
    end

  core.chat_send_all(message)
end)
