#include "pch.h"

#include "platform_windows/windows_lifecycle_state.h"

#include "platform_windows/windows_runtime_state.h"

namespace pp::platform::windows {
namespace {

struct RetainedWindowLifecycleState final {
    std::atomic<int> running{-1};
};

[[nodiscard]] RetainedWindowLifecycleState& retained_window_lifecycle_state() noexcept
{
    static RetainedWindowLifecycleState state;
    return state;
}

}

void mark_lifecycle_running() noexcept
{
    retained_lifecycle_running_state().store(1, std::memory_order_relaxed);
}

void mark_lifecycle_stopped() noexcept
{
    retained_lifecycle_running_state().store(0, std::memory_order_relaxed);
}

bool lifecycle_is_running() noexcept
{
    return retained_lifecycle_running_state().load(std::memory_order_relaxed) == 1;
}

std::atomic<int>& retained_lifecycle_running_state() noexcept
{
    return retained_window_lifecycle_state().running;
}

void shutdown_bound_lifecycle(VrShellState& vr)
{
    mark_lifecycle_stopped();
    request_stop_and_join_vr_thread(vr);
    shutdown_bound_app_runtime();
}

void shutdown_bound_lifecycle_and_quit(VrShellState& vr)
{
    shutdown_bound_lifecycle(vr);
    PostQuitMessage(0);
}

bool start_bound_lifecycle_vr(VrShellState& vr, bool sandboxed)
{
    return start_vr_shell(vr, sandboxed, retained_lifecycle_running_state());
}

void stop_bound_lifecycle_vr(VrShellState& vr)
{
    stop_vr_shell(vr);
}

}
