eb_transition = {}

local active_transition = nil
local active_shade = nil
local hud_handle = nil
local transition_timer = 0
local TRANSITION_STEP = 0.15
local SHADE_REDUCE = 32

local get_texture = function(stype)
	if stype == "death" then
		return "eb_transition_screen_death.png"
	elseif stype == "death_unseen" then
		return "eb_transition_screen_death.png"
	elseif stype == "death_seen_by_evil" then
		return "eb_transition_screen_death_seen_by_evil.png"
	elseif stype == "teleport" then
		return "eb_transition_screen_teleport.png"
	else
		return  "eb_transition_screen_death.png"
	end
end

local set_screen_type = function(stype)
	local player = core.get_player_by_name("singleplayer")
	if not player then
		return
	end
	if stype == "none" then
		if hud_handle then
			player:hud_remove(hud_handle)
			hud_handle = nil
		end
		return
	end
	local texture = get_texture(stype)
	if hud_handle then
		player:hud_change(hud_handle, "text", texture)
	else
		hud_handle = player:hud_add({
			type = "image",
			scale = { x = -100, y = -100 },
			position = { x = 0, y = 0 },
			alignment = { x = 1, y = 1 },
			text = texture,
			z_index = 1000,
		})
	end
end
local set_screen_shade = function(shade)
	active_shade = shade
	if hud_handle then
		local texture = get_texture(active_transition)
		if shade < 255 then
			texture = texture .. "^[opacity:"..shade
		end
		if hud_handle then
			local player = core.get_player_by_name("singleplayer")
			if player then
				player:hud_change(hud_handle, "text", texture)
			end
		end
	end
end

eb_transition.start_transition = function(ttype, initial_shade)
	set_screen_shade(initial_shade or 255)
	set_screen_type(ttype)
	active_transition = ttype
end

core.register_globalstep(function(dtime)
	if not active_transition then
		return
	end
	transition_timer = transition_timer + dtime
	if transition_timer < TRANSITION_STEP then
		return
	end
	transition_timer = 0
	active_shade = math.max(0, active_shade - SHADE_REDUCE)
	if active_shade == 0 then
		set_screen_type("none")
	else
		set_screen_shade(active_shade)
	end
end)
