-- LUALOCALS < ---------------------------------------------------------
local minetest, piredo_api, piredo_map, string
    = minetest, piredo_api, piredo_map, string
local string_match
    = string.match
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()
local modstore = minetest.get_mod_storage()

local storekey = "intro_sequence"
local function prevent_replay()
	modstore:set_string(storekey, "1")
end
local state = {
	done = (modstore:get_string(storekey) or "") ~= "" or nil
}

function api.introsequence(player, dtime)
	if state.done then return end

	if state.silence then
		state.silence = state.silence + dtime
		if state.silence >= 12 then
			state.silence = nil
			state.done = true
		end

	elseif state.event then
		state.event = state.event + dtime
		if state.event >= 42 then
			api.fade(9)
			state.event = nil
			state.silence = 0
		end

	elseif state.looptime then
		local _, area = piredo_map.get_map_area(player)
		if area and string_match(area, "^hall_") then
			state.looptime = state.looptime + dtime
			if state.looptime >= 5 then
				api.loopdj("first_realization", {seek = 0, force = true})
				state.looptime = 0
			end
		else
			api.loopdj("first_realization",
				{seek = 4, force = true, noloop = true})
			state.looptime = nil
			state.event = 0
			prevent_replay()
		end

	else
		local room = piredo_map.get_current_room()
		if room == "outside" then return end
		if room == "special_blocked" then return true end
		state.looptime = 0
		api.loopdj("first_realization", {seek = 0})
	end

	return true
end
