/*
 * Copyright (C) 2014-2024 CZ.NIC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QtGlobal>
#if defined(Q_OS_WIN)
#  include <windows.h>
#endif /* !Q_OS_WIN */

#include "src/datovka_shared/log/log.h"
#include "src/global.h" /* GlobInstcs::req_halt */
#include "src/system/win_console_handler.h"

#if defined(Q_OS_WIN)
static
BOOL WINAPI ConsoleHandler(DWORD dwType)
{
	GlobInstcs::req_halt = 1;
	switch(dwType) {
	case CTRL_C_EVENT:
		logInfoNL("%s",
		    "Ctrl+C pressed. Indicating a requested halt.");
		break;
	case CTRL_BREAK_EVENT:
		logInfoNL("%s",
		    "Ctrl+Break pressed. Indicating a requested halt.");
		break;
	default:
		logInfoNL("%s",
		    "Application requested to shut down. Indicating a requested halt.");
		break;
	}
	/*
	 * There's no way how to wait for the process to finish:
	 * https://stackoverflow.com/questions/47041407/why-does-my-windows-console-close-event-handler-time-out
	 * Just give the process some time to perform a clean up.
	 */
	Sleep(10000); // 10 seconds
	return TRUE;
}

static
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg) {
	case WM_QUERYENDSESSION:
		GlobInstcs::req_halt = 1;
		/*
		 * Check `lParam` for which system shutdown function and handle events.
		 * https://docs.microsoft.com/windows/win32/shutdown/wm-queryendsession
		 */
		//return TRUE; /* Respect user's intent and allow shutdown. */
		return FALSE; /* Tell the system that the app cannot quit immediately. */
		break;
	case WM_ENDSESSION:
		/*
		 * Check `lParam` for which system shutdown function and handle events.
		 * See https://docs.microsoft.com/windows/win32/shutdown/wm-endsession
		 */
		return 0; /* We have handled this message. */
		break;
	default:
		return DefWindowProc(hwnd, uMsg, wParam, lParam);
		break;
	}
}

int install_console_handlers(void)
{
	/*
	 * Listen with hidden window.
	 * https://learn.microsoft.com/en-us/windows/console/setconsolectrlhandler
	 * https://learn.microsoft.com/en-us/windows/console/registering-a-control-handler-function
	 */
	if (false) { /* This code doesn't seem to work. */
		static WNDCLASS sampleClass = {}; //{0};
		sampleClass.lpszClassName = TEXT("CtrlHandlerSampleClass");
		sampleClass.lpfnWndProc = WindowProc;

		if (!RegisterClass(&sampleClass)) {
			logErrorNL("%s", "Couldn't register window class.");
			return -1;
		}

		static HWND hwnd = CreateWindowEx(
		    0,
		    sampleClass.lpszClassName,
		    TEXT("Console Control Handler Sample"),
		    0,
		    CW_USEDEFAULT,
		    CW_USEDEFAULT,
		    CW_USEDEFAULT,
		    CW_USEDEFAULT,
		    nullptr,
		    nullptr,
		    nullptr,
		    nullptr
		);

		if (!hwnd) {
			logErrorNL("%s", "Couldn't create window.");
			return -1;
		}

		ShowWindow(hwnd, SW_HIDE);
	}

	if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE)) {
		return -1;
	}

	return 0;
}
#endif /* !Q_OS_WIN */
