/*
 * Copyright (C) 2014-2023 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 <QByteArray>
#if defined(Q_OS_WIN)
#  include <windows.h>
#endif /* !Q_OS_WIN */

/*
 * https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg
 * https://www.apriorit.com/dev-blog/413-win-api-shutdown-events
 */

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

#if defined(Q_OS_WIN)
bool NativeEventFilter::nativeEventFilter(const QByteArray &eventType,
    void *message,
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
    qintptr
#else /* < Qt-6.0 */
    long
#endif /* >= Qt-6.0 */
    *result)
{
	static const QByteArray genericMSG("windows_generic_MSG");
	static const QByteArray dispatcherMSG("windows_dispatcher_MSG");

	if ((eventType == genericMSG) || (eventType == dispatcherMSG)) {
		MSG *msg = (MSG *)message;
		if (Q_UNLIKELY(msg == NULL)) {
			return false;
		}
		switch (msg->message) {
		case WM_POWERBROADCAST:
			if (msg->wParam == PBT_APMSUSPEND) {
				/* Computer is suspending. */
				/* Do nothing. */
			}
			break;
		case WM_QUERYENDSESSION:
			GlobInstcs::req_halt = 1;
			if (msg->lParam == 0) {
				/* Computer is shutting down. */
				logInfoNL("%s",
				    "Computer is shutting down. Indicating a requested halt.");
			} else if ((msg->lParam & ENDSESSION_LOGOFF) == ENDSESSION_LOGOFF) {
				/* User is logging off. */
				logInfoNL("%s",
				    "User is logging off. Indicating a requested halt.");
			} else {
				logInfoNL("%s",
				    "Application requested to shut down. Indicating a requested halt.")
			}
			if (result != NULL) {
				/*
				 * Tell the system that the app cannot quit
				 * immediately.
				 */
				*result = false;
				/*
				 * Prevent Qt from further processing this event
				 * because it messes with the result value.
				 */
				return true;
			}
			break;
		default:
			break;
		}
	}

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