#include "ApplicationData.h"
#include "ImguiBase.h"
#include "Util.h"
#include "Settings.h"

extern bool justDocked;
extern DrawData* gDrawData;
extern ApplicationData* gAppData;

void initSettings(DrawData& drawData, ApplicationData& appData)
{
	ImGuiSettingsHandler ini_handler;
	ini_handler.TypeName = "ApplicationSettings";
	ini_handler.TypeHash = ImHashStr("ApplicationSettings");
	ini_handler.ReadOpenFn = settingsReadOpen;
	ini_handler.ReadLineFn = settingsReadLine;
	ini_handler.WriteAllFn = settingsWriteAll;
	GImGui->SettingsHandlers.push_back(ini_handler);
	ImGui::LoadIniSettingsFromDisk("imgui.ini");
	applySettings(drawData, appData);
}

void* settingsReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name)
{
	ApplicationSettings* settings = &gAppData->settings;
	*settings = ApplicationSettings();
	return (void*)settings;
}

void settingsReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line)
{
	ApplicationSettings* settings = (ApplicationSettings*)entry;

	int docked;
	if (sscanf_s(line, "docked=%i", &docked))
	{
		settings->docked = (bool)docked;
	}
	int autostart;
	if (sscanf_s(line, "autostart=%i", &autostart))
	{
		settings->autostart = (bool)autostart;
	}
}

void settingsWriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* outBuf)
{
	outBuf->appendf("[%s][%s]\n", "ApplicationSettings", "ApplicationSettings");
	outBuf->appendf("docked=%i\n", (int)gAppData->settings.docked);
	outBuf->appendf("autostart=%i\n", (int)gAppData->settings.autostart);
	outBuf->append("\n");
}

void applySettings(DrawData& drawData, ApplicationData& appData)
{
	updateDocked(drawData, appData);
	setAutostart(appData.settings.autostart);
}

void updateDocked(DrawData& drawData, ApplicationData& appData)
{
	justDocked = true;

	glfwSetWindowAttrib(drawData.window, GLFW_DECORATED, !appData.settings.docked);
	ShowWindow(drawData.window_handle, SW_HIDE);
	SetWindowLongPtr(drawData.window_handle, GWL_EXSTYLE, appData.settings.docked ? WS_EX_TOOLWINDOW : 0);
	ShowWindow(drawData.window_handle, SW_SHOW);
}

void setAutostart(bool newValue)
{
	const size_t MAX_PATH_LENGTH = 2048;
	const wchar_t* KEY_APP_NAME = L"AsuroTool";

	HRESULT hr;

	HKEY runKey = nullptr;
	hr = RegCreateKey(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &runKey);
	if (isError(hr, "Failed to find/create autostart run key: ")) return;

	if (newValue)
	{
		std::wstring appPath;
		if (FAILED(getAppPath(appPath))) return;

		hr = RegSetValueEx(runKey, KEY_APP_NAME, 0, REG_SZ, (BYTE*)appPath.c_str(), static_cast<DWORD>((appPath.size() + 1) * sizeof(wchar_t)));
		if (isError(hr, "Failed to write autostart key: ")) return;
	}
	else
	{
		hr = RegDeleteValue(runKey, KEY_APP_NAME);
		if (isError(hr, "Failed to delete autostart key: ")) return;
	}
}
