-- Load default configuration andf functions
local modpath = minetest.get_modpath(minetest.get_current_modname())..DIR_DELIM
local config = dofile(modpath..'system'..DIR_DELIM..'get_options.lua')
dofile(modpath..'system'..DIR_DELIM..'timer_function.lua')


-- Set custom player attribute if not set
--
-- Sets a custom player attribute if the attribute is not set already.
--
-- @param player     The player opbject of the player to set the attribute for
-- @param attribute  The attribute to set if not present
-- @param value      The value to be set if the attribute does not exist
local set_if_unset = function(player, attribute, value)
    local current_value = player:get_attribute(attribute)
    if current_value == nil then player:set_attribute(attribute, value) end
end


-- Get a position table from a comma-separated position string
--
-- @param position_string The desired position in `x,y` format
--
-- @return table The position table
mtimer_position = function (position_string)
    local given_x = position_string:gsub(',[^,]+$', '')
    local given_y = position_string:gsub('^[^,]+,', '')
    return {x=given_x, y=given_y}
end


minetest.register_on_joinplayer(function(player)
    -- Set default values if not present
    set_if_unset(player, 'mtimer:runtime', config['mtimer_runtime'])
    set_if_unset(player, 'mtimer:offset', config['mtimer_offset'])
    set_if_unset(player, 'mtimer:ingame_time', config['mtimer_ingame_time'])
    set_if_unset(player, 'mtimer:current_time', config['mtimer_current_time'])
    set_if_unset(player, 'mtimer:font_color', config['mtimer_font_color'])
    set_if_unset(player, 'mtimer:start', config['mtimer_start'])
    set_if_unset(player, 'mtimer:show', config['mtimer_show'])
    set_if_unset(player, 'mtimer:locale', config['mtimer_locale'])
    set_if_unset(player, 'mtimer:position', config['mtimer_position'])
    set_if_unset(player, 'mtimer:format', config['mtimer_format'])
    set_if_unset(player, 'mtimer:alignment', config['mtimer_alignment'])

    -- Set join timestamp for later calculations
    player:set_attribute('mtimer:joined_timestamp', os.time())

    -- Set the hud element ID for later usage and set text to the placeholder
    player:set_attribute('mtimer:hud_id', player:hud_add({
        hud_elem_type = 'text',
        position = mtimer_position(player:get_attribute('mtimer:position')),
        alignment = mtimer_position(player:get_attribute('mtimer:alignment')),
        offset = mtimer_position(player:get_attribute('mtimer:offset')),
        text = config['mtimer_placeholder'],
        number = '0x'..player:get_attribute('mtimer:font_color')
    }))

    -- Run inital update for the player
    minetest.after(1, mtimer_update, player)
end)

-- Start iteration after 5 seconds
minetest.after(5, mtimer_iterate, tonumber(config['mtimer_update_interval']))