#include "ClipboardUtils.h"
#include <cstdio>
#include <algorithm>

bool ClipboardUtils::CopyColor(int r, int g, int b, int a) {
	char buf[32];
	sprintf_s(buf, sizeof(buf), "%d,%d,%d,%d", r, g, b, a);
	if (!OpenClipboard(NULL))
		return false;
	EmptyClipboard();
	HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, strlen(buf) + 1);
	if (!hMem) {
		CloseClipboard();
		return false;
	}
	char* p = (char*)GlobalLock(hMem);
	strcpy_s(p, strlen(buf) + 1, buf);
	GlobalUnlock(hMem);
	SetClipboardData(CF_TEXT, hMem);
	CloseClipboard();
	return true;
}

bool ClipboardUtils::PasteColor(int col[4]) {
	if (!OpenClipboard(NULL))
		return false;
	HANDLE hData = GetClipboardData(CF_TEXT);
	if (!hData) { CloseClipboard(); return false; }
	char* p = (char*)GlobalLock(hData);
	if (!p) { CloseClipboard(); return false; }
	int r = 255, gv = 255, b = 255, a = 255;
	int parsed = sscanf_s(p, "%d,%d,%d,%d", &r, &gv, &b, &a);
	GlobalUnlock(hData);
	CloseClipboard();
	if (parsed >= 3) {
		col[0] = std::clamp(r, 0, 255);
		col[1] = std::clamp(gv, 0, 255);
		col[2] = std::clamp(b, 0, 255);
		col[3] = (parsed >= 4) ? std::clamp(a, 0, 255) : 255;
		return true;
	}
	return false;
}

bool ClipboardUtils::HasText() {
	if (!OpenClipboard(NULL))
		return false;
	bool has = IsClipboardFormatAvailable(CF_TEXT) != 0;
	CloseClipboard();
	return has;
}
