#pragma once

#include "PreviewConfig.h"

#include "../frames/SystemFrameTypes.h"

#include <atomic>
#include <thread>
#include <vector>

#ifndef NOMINMAX
#define NOMINMAX
#endif

#include <windows.h>

class SystemFrameExchange;

namespace RenderCadenceCompositor
{
class PreviewWindowThread
{
public:
	PreviewWindowThread() = default;
	PreviewWindowThread(const PreviewWindowThread&) = delete;
	PreviewWindowThread& operator=(const PreviewWindowThread&) = delete;
	~PreviewWindowThread();

	bool Start(SystemFrameExchange& exchange, const PreviewWindowConfig& config, std::string& error);
	void Stop();
	bool Running() const { return mRunning.load(std::memory_order_acquire); }

	static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam);

private:
	void ThreadMain();
	bool CreatePreviewWindow(std::string& error);
	void Paint(HWND window);
	bool CopyPreviewOrientedBgra8Frame(const SystemFrame& frame);

	SystemFrameExchange* mExchange = nullptr;
	PreviewWindowConfig mConfig;
	std::vector<unsigned char> mPaintPixels;
	bool mLoggedPaintCopyFailure = false;
	std::thread mThread;
	std::atomic<bool> mStopRequested{ false };
	std::atomic<bool> mRunning{ false };
	std::atomic<DWORD> mThreadId{ 0 };
	HWND mWindow = nullptr;
};
}
