local vector2 = require("#microsoft.xna.framework.vector2")
local monocle = require("#monocle")
local lua_helper = celeste.Mod.LuaCutscenes.LuaHelper

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

function onBegin()
    not_cameraing = true
    done_cameraing = false
    player.ForceCameraUpdate = true
    engine.Scene:ResetZoom()
    playMusic("event:/AnEnormousSmileyFace/no-rest-three")
    disableMovement()
    camera_coroutine = makeCoroutine(cameraController)
    cutsceneEntity:Add(camera_coroutine)
    engine.Scene:ZoomSnap(vector2(160, 94), 2)
    wait(12)
    setFlag("darkness_fade", false)
    walk(10)
    wait(0.25)
    not_cameraing = false
    wait(0.25)
    walk(30)
    wait(0.5)
    walk(-20)
    wait(0.5)
    walk(40)
    wait(0.5)
    walk(-30)
    wait(0.5)
    walk(-10)
    wait(0.5)
    walk(-30)
    wait(0.5)
    walk(10)
    wait(0.5)
    walk(-25)
    wait(1.8)
    setFlag("tv_0", true)
    setFlag("tv_play", true)
    setFlag("tv_call", true)
    wait(2.9)
    setFlag("darkness_fade", true)
    coroutine.yield(engine.Scene:ZoomAcross(vector2(97.5, 115), 47, 0.5))
end

function cameraController()
    while (not_cameraing) do
        wait()
    end
    target_x = 104
    target_y = 116
    target_z = 6
    start_x = 160
    start_y = 94
    start_z = 2
    duration = 600
    x_dist = (target_x - start_x) / duration
    y_dist = (target_y - start_y) / duration
    z_dist = (target_z - start_z) / duration
    t = 0
    while (t < duration) do
        engine.Scene:ZoomSnap(vector2(start_x + x_dist * t, start_y + y_dist * t), start_z + z_dist * t*t / (duration))
        wait()
        t = t + 1
    end
    done_cameraing = true
    while (true) do
        wait()
    end
end

function onEnd()
    if camera_coroutine then
        camera_coroutine:Cancel()
        cutsceneEntity:Remove(camera_coroutine)
    end
    engine.Scene:ResetZoom()
    enableMovement()
    --playMusic("")
    instantTeleportTo(1056, -128, "END-03")
end

