#pragma once

#include "RuntimeLayerModel.h"
#include "RuntimeJson.h"

#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <mutex>
#include <string>
#include <thread>

namespace RenderCadenceCompositor
{
JsonValue RuntimeStateSnapshotToJson(const RuntimeLayerModelSnapshot& snapshot);
std::string SerializeRuntimeStateSnapshot(const RuntimeLayerModelSnapshot& snapshot);

class RuntimeStatePersistenceWriter
{
public:
	RuntimeStatePersistenceWriter() = default;
	RuntimeStatePersistenceWriter(const RuntimeStatePersistenceWriter&) = delete;
	RuntimeStatePersistenceWriter& operator=(const RuntimeStatePersistenceWriter&) = delete;
	~RuntimeStatePersistenceWriter();

	void Start(const std::filesystem::path& path, std::chrono::milliseconds debounce);
	void RequestSave(const RuntimeLayerModelSnapshot& snapshot);
	void Stop(bool flushPending = true);

private:
	void ThreadMain();
	bool WriteSnapshot(const std::string& serializedState, std::string& error) const;

	std::filesystem::path mPath;
	std::chrono::milliseconds mDebounce{ 250 };
	std::mutex mMutex;
	std::condition_variable mCondition;
	std::thread mThread;
	std::string mPendingState;
	bool mHasPendingState = false;
	bool mStopping = false;
};
}
