--[[ init.lua
Copyright 2025 Pixelo789

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

SPDX-License-Identifier: AGPL-3.0-or-later
--]]


thinkingwitharrows_transitions = {}
local modname = core.get_current_modname()
local S = core.get_translator(modname)

local huds = {}


function thinkingwitharrows_transitions._add_transition(player, level)
	local name = player:get_player_name()

	-- compatibility with older versions of Luanti
	local hud_type
	if core.features.hud_def_type_field then
		hud_type = "type"
	else
		hud_type = "hud_elem_type"
	end

	local oldhud = huds[name]

	local texture_name = "thinkingwitharrows_init_black_box.png^[opacity:" .. level
	if oldhud then
		player:hud_change(oldhud, "text", texture_name)
	else
		huds[name] = player:hud_add {
			[hud_type] = "image",
			alignment = {x = 1, y = 1},
			z_index = 1000,
			scale = {x = -100, y = -100}, -- fullscreen
			text = texture_name,
		}
	end
end


function thinkingwitharrows_transitions._remove_transition(player)
	local name = player:get_player_name()

	if huds[name] then
		player:hud_remove(huds[name])
		huds[name] = nil
	end
end


function thinkingwitharrows_transitions.queue_transition(player)
	local meta = player:get_meta()

	local a = thinkingwitharrows_transitions._add_transition
	local r = thinkingwitharrows_transitions._remove_transition
	for i = 1, 255, 2 do
		-- fade in
		core.after(i / 341, function()
			a(player, i)
		end)
		-- fade out
		core.after(2.5 - i / 341, function()
			a(player, i)
		end)
	end

	core.after(256/341, function()
		player:set_pos({x = -3, y = 0.5, z = 1})
	end)

	core.after(2.5, function()
		r(player)
		meta:set_int("transitioning", 0)
	end)

	meta:set_int("transitioning", 1)
end
