-- cutscene for when the blocks collapse

--set up coroutine stuff
local lua_helper = celeste.Mod.LuaCutscenes.LuaHelper
local monocle = require("#monocle")

local function makeCoroutine(func)
	return monocle.Coroutine(lua_helper.LuaCoroutineToIEnumerator(coroutine.create(func)))
end

--functions
function moveCameraSmoothly(startx, starty, endx, endy, duration_ms)
	local dx = (endx - startx) / duration_ms
	local dy = (endy - starty) / duration_ms
	for i=0,duration_ms do
		setCameraOffset(startx + dx * i * 10, starty + dy * i * 10)
		wait(0.01)
	end
end

function getAllBlocks()
    return getAllEntities("Mod.FancyTileEntities.BetterIntroCrusher")
end

function triggerAllBlocks()
    for index, tile in ipairs(getAllBlocks()) do
        tile.Trigger(tile)
    end
end

function disableAllBlocks()
    for index, tile in ipairs(getAllBlocks()) do 
        tile.Active = false;
        tile.Visible = false;
        tile.Collidable = false;
    end
end

--actual cutscene stuff

local smoothCameraMoveCoroutine

function onBegin()
	--don't do the cutscene twice.  make sure blocks start and ending position if we don't run the cutscene
	local ran_before = getFlag("nilrem_collapsing_cathedral_collapse_cutscene_ran")
	if not ran_before then 
		setFlag("nilrem_collapsing_cathedral_collapse_cutscene_ran", true)
	else
        disableAllBlocks()
		endCutscene()
		return
	end

	player.ForceCameraUpdate = true
	disableMovement()
    disableRetry()
	
	smoothCameraMoveCoroutine = makeCoroutine(function() 
		moveCameraSmoothly(-3, 0, -17, 2, 1500)
	end)
	cutsceneEntity:Add(smoothCameraMoveCoroutine)
	
    wait(0.5)
    triggerAllBlocks()
	wait(3.5)
end

function onEnd(room, wasSkipped)

	if smoothCameraMoveCoroutine then
		smoothCameraMoveCoroutine:Cancel()
		cutsceneEntity:Remove(smoothCameraMoveCoroutine)
	end
    
    disableAllBlocks()
	enableMovement()
	setCameraOffset(0, 0)
end
