/*
 * Copyright (C) 2014-2026 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.
 */

#if defined(__APPLE__) || defined(__clang__)
#  define __USE_C99_MATH
#  define _Bool bool
#else /* !__APPLE__ */
#  include <stdbool.h>
#endif /* __APPLE__ */

#include <cstdlib>
#include <cstring>
#include <libdatovka/isds.h>

#include "src/isds/internal_conversion.h"

QDateTime Isds::dateTimeFromStructTimeval(struct isds_timeval *cDateTime)
{
	QDateTime timeStamp;

	if (cDateTime != NULL) {
		/* TODO -- handle microseconds. */
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
		timeStamp.setSecsSinceEpoch(cDateTime->tv_sec);
#else /* < Qt-5.8 */
		/* Don't use QDateTime::setTime_t because it takes uint. */
		timeStamp.setMSecsSinceEpoch(cDateTime->tv_sec * 1000);
#endif /* >= Qt-5.8 */
		timeStamp = timeStamp.addMSecs(cDateTime->tv_usec / 1000);
	}

	return timeStamp;
}

bool Isds::toCDateTimeCopy(struct isds_timeval **cDateTimePtr,
    const QDateTime &dateTime)
{
	if (Q_UNLIKELY(cDateTimePtr == Q_NULLPTR)) {
		Q_ASSERT(0);
		return false;
	}
	if (dateTime.isNull()) {
		if (*cDateTimePtr != NULL) {
			/* Delete allocated. */
			::std::free(*cDateTimePtr); *cDateTimePtr = NULL;
		}
		return true;
	}
	if (*cDateTimePtr == NULL) {
		*cDateTimePtr =
		    (struct isds_timeval *)::std::malloc(sizeof(**cDateTimePtr));
		if (Q_UNLIKELY(*cDateTimePtr == NULL)) {
			Q_ASSERT(0);
			return false;
		}
	}
	::std::memset(*cDateTimePtr, 0, sizeof(**cDateTimePtr));

	/* TODO -- handle microseconds. */
#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))
	(*cDateTimePtr)->tv_sec = dateTime.toSecsSinceEpoch();
#else /* < Qt-5.8 */
	/* Don't use QDateTime::toTime_t() because it returns uint. */
	(*cDateTimePtr)->tv_sec = dateTime.toMSecsSinceEpoch() / 1000;
#endif /* >= Qt-5.8 */
	(*cDateTimePtr)->tv_usec = dateTime.time().msec() * 1000;
	return true;
}
