/*
 * 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.
 */

#include <QApplication>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
#  include <QWindow>
#else /* < Qt-5.14 */
#  include <QDesktopWidget>
#endif /* >= Qt-5.14 */
#include <QFontMetrics>
#include <QGuiApplication>
#include <QHeaderView>
#include <QScreen>
#include <QSplitter>
#include <QStyleOption>
#include <QTableView>

#include "src/datovka_shared/log/log.h"
#include "src/dimensions/dimensions.h"

const qreal Dimensions::m_margin = 0.4;
const qreal Dimensions::m_padding = 0.1;
const qreal Dimensions::m_lineHeight = 1.35;
const qreal Dimensions::m_screenRatio = 0.8;
const QRect Dimensions::m_dfltWinRect(40, 40, 400, 300);

/*!
 * @brief Obtain default widget font height.
 *
 * @param[in] widget Pointer to widget.
 * @return Font heigh in pixels.
 */
static inline
int fontHeight(const QWidget *widget)
{
	Q_ASSERT(Q_NULLPTR != widget);

	QStyleOption option;
	option.initFrom(widget);
	return option.fontMetrics.height();
}

int Dimensions::margin(const QStyleOptionViewItem &option)
{
	return QFontMetrics(option.font).height() * m_margin;
}

int Dimensions::padding(int height)
{
	return height * m_padding;
}

int Dimensions::tableLineHeight(const QStyleOptionViewItem &option)
{
	return QFontMetrics(option.font).height() * m_lineHeight;
}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
/*
 * There's QWidget::screen() since Qt-5.14 -- see the sources.
 * There's QGuiApplication::screenAt() since Qt-5.10.
 * https://stackoverflow.com/questions/49167204/find-screen-a-qwidget-is-located-on/53490851
 */
static
QScreen *getScreen(const QWidget *widget)
{
	if (Q_UNLIKELY(widget == Q_NULLPTR)) {
		logErrorNL("%s", "Could not determine the screen.");
		return Q_NULLPTR;
	}

	return widget->screen();
}
#else /* < Qt-5.14 */
/*!
 * @brief Obtain pointer to screen.
 *
 * @return Pointer to screen, Q_NULLPTR on error.
 */
static
QScreen *getScreen(const QWidget *widget)
{
	Q_UNUSED(widget);

	int screenNum = QApplication::desktop()->screenNumber();
	if (Q_UNLIKELY(screenNum < 0)) {
		logErrorNL("%s", "Could not determine screen number.");
		return Q_NULLPTR;
	}
	QList<QScreen *> screens = QGuiApplication::screens();
	if (screenNum < screens.size()) {
		logDebugLv0NL("Using screen index %d out of %d.",
		    screenNum, screens.size());
		return screens[screenNum];
	} else {
		logErrorNL("Could not access data for screen %d.", screenNum);
	}

	return Q_NULLPTR;
}
#endif /* >= Qt-5.14 */

#define RECT_WIDTH 1024
#define RECT_HEIGHT 768

QRect Dimensions::availableScreenSize(const QWidget *widget)
{
	QScreen *screen = getScreen(widget);
	if (Q_UNLIKELY(screen == Q_NULLPTR)) {
		logWarningNL("Using default screen size (%dx%x).", RECT_WIDTH, RECT_HEIGHT);
		return QRect(0, 0, RECT_WIDTH, RECT_HEIGHT);
	}
	return screen->availableGeometry();
}

QRect Dimensions::screenSize(const QWidget *widget)
{
	QScreen *screen = getScreen(widget);
	if (Q_UNLIKELY(screen == Q_NULLPTR)) {
		logWarningNL("Using default screen size (%dx%x).", RECT_WIDTH, RECT_HEIGHT);
		return QRect(0, 0, RECT_WIDTH, RECT_HEIGHT);
	}
	return screen->geometry();
}

QSize Dimensions::windowSize(const QWidget *widget, qreal wr, qreal hr)
{
	if (Q_UNLIKELY((widget == Q_NULLPTR) || (wr <= 0.0) || (hr <= 0.0))) {
		return QSize();
	}

	int height = fontHeight(widget);
	int w = height * wr;
	int h = height * hr;

	/* Reduce window with if it exceeds screen width. */
	QRect screenRect = screenSize(widget);

	if (screenRect.width() < w) {
		qreal ratio =
		    (qreal)w / ((qreal)screenRect.width() * m_screenRatio);
		w /= ratio;
		h *= ratio;
	}

	return QSize(w, h);
}

/*!
 * @brief Compute difference between window frame and its actual size.
 *
 * @param[in] widget Window widget.
 * @return Absolute difference between frame and window geometry.
 */
static
QRect frameDifference(const QWidget *widget)
{
	if (Q_UNLIKELY(widget == Q_NULLPTR)) {
		return QRect(0, 0, 0, 0);
	}

	QRect windowRect(widget->geometry());
	QRect frameRect(widget->frameGeometry());

	/* Frame differences don't work on X11. */
	int x = frameRect.x() - windowRect.x();
	int y = frameRect.y() - windowRect.y();
	if (x < 0) {
		x = -x;
	}
	if (y < 0) {
		y = -y;
	}

	int w = frameRect.width() - windowRect.width();
	int h = frameRect.height() - windowRect.height();
	if (w < 0) {
		w = -w;
	}
	if (h < 0) {
		h = -h;
	}

	return QRect(x, y, w, h);
}

QRect Dimensions::windowDimensions(const QWidget *widget, qreal wr, qreal hr)
{
	if (Q_UNLIKELY(widget == Q_NULLPTR)) {
		return m_dfltWinRect;
	}

	int x = 0; /* top */
	int y = 0; /* left */
	int w = 400; /* width */
	int h = 300; /* height */

	/* Reduce dimensions if they exceed screen width. */
	QRect availRect(availableScreenSize(widget));

	if (wr <= 0.0 || hr <= 0.0) {
		/* Use available screen space to compute geometry. */
		QRect diffRect(frameDifference(widget));

		//int right = diffRect.width() - diffRect.x();
		int bottom = diffRect.height() - diffRect.y();

		if (diffRect.y() != 0) {
			w = availRect.width() - (2 * (diffRect.y() + bottom));
			h = availRect.height() - (2 * (diffRect.y() + bottom));
		} else {
			w = availRect.width() * m_screenRatio;
			h = availRect.height() * m_screenRatio;
		}
	} else {
		/* Use font height to determine window size. */
		int fh = fontHeight(widget);
		w = fh * wr;
		h = fh * hr;

		if (availRect.width() < w) {
			w = availRect.width() * m_screenRatio;
		}
		if (availRect.height() < h) {
			h = availRect.height() * m_screenRatio;
		}
	}

	/* Compute centred window position. */
	x = availRect.x() + ((availRect.width() - w) / 2);
	y = availRect.y() + ((availRect.height() - h) / 2);

	return QRect(x, y, w, h);
}

QRect Dimensions::windowOnScreenDimensions(const QWidget *widget)
{
	if (Q_UNLIKELY(widget == Q_NULLPTR)) {
		return m_dfltWinRect;
	}

	QRect frameRect(widget->frameGeometry());
	QRect availRect(availableScreenSize(widget));

	if ((frameRect.width() > availRect.width()) ||
	    (frameRect.height() > availRect.height())) {
		/*
		 * Window is too large. Position the window in the centre of
		 * available space.
		 */
		return windowDimensions(widget, -1.0, -1.0);
	}

	/* Negative values mean the window exceeds screen border. */
	int beyondLeft = frameRect.topLeft().x() - availRect.topLeft().x();
	int beyondTop = frameRect.topLeft().y() - availRect.topLeft().y();
	int beyondRight =
	    availRect.bottomRight().x() - frameRect.bottomRight().x();
	int beyondBottom =
	    availRect.bottomRight().y() - frameRect.bottomRight().y();

	QRect windowRect(widget->geometry());

	if (beyondLeft < 0) {
		windowRect.moveLeft(windowRect.topLeft().x() - beyondLeft);
	}
	if (beyondTop < 0) {
		windowRect.moveTop(windowRect.topLeft().y() - beyondTop);
	}
	if (beyondRight < 0) {
		windowRect.moveLeft(windowRect.topLeft().x() + beyondRight);
	}
	if (beyondBottom < 0) {
		windowRect.moveTop(windowRect.topLeft().y() + beyondBottom);
	}

	return windowRect;
}

QSize Dimensions::dialogueSize(const QWidget *widget, const QSize &newSize, const QSize &defSize)
{
	if (Q_UNLIKELY(widget == Q_NULLPTR)) {
		return defSize;
	}

	/* New size is invalid or zero, return default size. */
	if (Q_UNLIKELY((newSize.width() <= 0) || (newSize.height() <= 0))) {
		return defSize;
	}

	/* Get dimensions of used screen. */
	QRect availRect(availableScreenSize(widget));

	if ((newSize.width() > availRect.width()) ||
	    (newSize.height() > availRect.height())) {
		/* New size too large, use defaults. */
		return defSize;
	}

	return newSize;
}

QVector<double> Dimensions::relativeTableColumnWidths(const QTableView *table)
{
	/* Clear prefs. */
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return QVector<double>();
	}

	const qint64 tabWidth = table->width();

	/* Clear prefs. */
	if (Q_UNLIKELY((tabWidth <= 0) || (Q_NULLPTR == table->model())
	        || (table->model()->columnCount() <= 0))) {
		return QVector<double>();
	}

	double colWidth = 0.0;
	QVector<double> columnRatios;

	/* Remember new relative width. */
	const int columnCount = table->model()->columnCount();
	columnRatios.resize(columnCount);
	for (int i = 0; i < columnCount; ++i) {
		if (table->columnWidth(i) <= 0) {
			colWidth = 0.0;
		} else {
			colWidth = ((double)table->columnWidth(i)) / tabWidth;
		}
		columnRatios[i] = colWidth;
	}

	return columnRatios;
}

void Dimensions::setRelativeTableColumnWidths(QTableView *table,
    const QVector<double> &relativeWidths)
{
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return;
	}

	/* Use default width. */
	if (Q_UNLIKELY(relativeWidths.size() == 0)) {
		return;
	}

	const qint64 tabWidth = table->width();

	/* Use default width. */
	if (Q_UNLIKELY((tabWidth <= 0) || (Q_NULLPTR == table->model()))) {
		return;
	}

	int columnCount = table->model()->columnCount();
	if (Q_UNLIKELY(relativeWidths.size() < columnCount)) {
		columnCount = relativeWidths.size();
	}

	/* Compute and set column width due table width. */
	double colWidth = 0.0;
	for (int i = 0; i < columnCount; ++i) {
		if (Q_UNLIKELY(table->isColumnHidden(i))) {
			continue;
		} else if (relativeWidths.at(i) <= 0.0) {
			table->setColumnWidth(i, 0);
		} else {
			colWidth = relativeWidths.at(i) * tabWidth;
			table->setColumnWidth(i, colWidth);
		}
	}
}

QVector<qint64> Dimensions::tableColumnWidths(const QTableView *table)
{
	/* Clear prefs. */
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return QVector<qint64>();
	}

	/* Clear prefs. */
	if (Q_UNLIKELY((Q_NULLPTR == table->model())
	        || (table->model()->columnCount() <= 0))) {
		return QVector<qint64>();
	}

	QVector<qint64> colWidths;

	/* Remember new width. */
	const int columnCount = table->model()->columnCount();
	colWidths.resize(columnCount);
	for (int i = 0; i < columnCount; ++i) {
		if (table->columnWidth(i) <= 0) {
			colWidths[i] = 0;
		} else {
			colWidths[i] = table->columnWidth(i);
		}
	}

	return colWidths;
}

void Dimensions::setTableColumnWidths(QTableView *table,
    const QVector<qint64> &widths)
{
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return;
	}

	/* Use default width. */
	if (Q_UNLIKELY((widths.size() == 0) || (Q_NULLPTR == table->model()))) {
		return;
	}

	int columnCount = table->model()->columnCount();
	if (Q_UNLIKELY(widths.size() < columnCount)) {
		columnCount = widths.size();
	}

	for (int i = 0; i < columnCount; ++i) {
		if (Q_UNLIKELY(table->isColumnHidden(i))) {
			continue;
		} else if (widths.at(i) <= 0) {
			table->setColumnWidth(i, 0);
		} else {
			table->setColumnWidth(i, widths.at(i));
		}
	}
}

int Dimensions::splitterSize(const QSplitter *splitter)
{
	if (Q_UNLIKELY(splitter == Q_NULLPTR)) {
		return -1;
	}

	const QList<int> sizes = splitter->sizes();
	if (Q_UNLIKELY(sizes.isEmpty())) {
		return -1;
	}

	return splitter->sizes().at(0);
}

/*!
 * @brief Get splitter size in the axis in which the splitter moves.
 *
 * @param[in] splitter Splitter.
 * @return Relevant splitter size.
 */
static inline
int relevantSplitterSize(const QSplitter &splitter)
{
	int totalSize = 0;

	switch (splitter.orientation()) {
	case Qt::Horizontal:
		totalSize = splitter.size().width();
		break;
	case Qt::Vertical:
		totalSize = splitter.size().height();
		break;
	default:
		Q_ASSERT(0);
		break;
	}

	return totalSize;
}

void Dimensions::setSplitterSize(QSplitter *splitter, int paneSize)
{
	if (Q_UNLIKELY(splitter == Q_NULLPTR)) {
		return;
	}

	if (Q_UNLIKELY(paneSize < 0)) {
		return;
	}

	QList<int> sizes = splitter->sizes();
	const int total = relevantSplitterSize(*splitter);

	sizes[0] = paneSize;
	sizes[1] = total - splitter->handleWidth() - paneSize;
	splitter->setSizes(sizes);
}

QVector<double> Dimensions::relativeSplitterSizes(const QSplitter *splitter)
{
	QVector<double> relativeSizes;

	if (Q_UNLIKELY(Q_NULLPTR == splitter)) {
		return relativeSizes;
	}

	qint64 totalSize = relevantSplitterSize(*splitter);

	if (Q_UNLIKELY(totalSize <= 0)) {
		return relativeSizes;
	}

	const QList<int> sizes = splitter->sizes();
	relativeSizes.resize(sizes.size());
	for (int i = 0; i < sizes.size(); ++i) {
		relativeSizes[i] = ((double)sizes.at(i)) / ((double)totalSize);
	}

	return relativeSizes;
}

void Dimensions::setRelativeSplitterSizes(QSplitter *splitter,
    const QVector<double> &relativeSizes)
{
	if (Q_UNLIKELY(Q_NULLPTR == splitter)) {
		return;
	}

	/* Use default width. */
	if (Q_UNLIKELY(relativeSizes.size() == 0)) {
		return;
	}

	qint64 totalSize = relevantSplitterSize(*splitter);

	if (Q_UNLIKELY(totalSize <= 0)) {
		return;
	}

	QList<int> sizes = splitter->sizes();

	int fields = relativeSizes.size();

	if (Q_UNLIKELY((sizes.size() < fields))) {
		fields = sizes.size();
	}

	for (int i = 0; i < fields; ++i) {
		sizes[i] = relativeSizes.at(i) * totalSize;
	}

	splitter->setSizes(sizes);
}

#define COL_POS 0
#define SORT_POS 1
#define ASCENDING_VAL 0
#define DESCENDING_VAL 1

QVector<int> Dimensions::tableColumnSortOrder(const QTableView *table)
{
	/* Clear prefs. */
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return QVector<int>();
	}

	/* Clear prefs. */
	if (Q_UNLIKELY(!table->isSortingEnabled())) {
		return QVector<int>();
	}

	/* Clear prefs. */
	if (Q_UNLIKELY(!table->horizontalHeader()->isSortIndicatorShown())) {
		return QVector<int>();
	}

	QVector<int> vs(2);
	vs[COL_POS] = table->horizontalHeader()->sortIndicatorSection();
	vs[SORT_POS] =
	    (table->horizontalHeader()->sortIndicatorOrder() == Qt::AscendingOrder)
	        ? ASCENDING_VAL : DESCENDING_VAL;

	return vs;
}

void Dimensions::setTableColumnSortOrder(QTableView *table,
    const QVector<int> &columnAndOrder)
{
	if (Q_UNLIKELY(table == Q_NULLPTR)) {
		return;
	}

	if (Q_UNLIKELY(!table->isSortingEnabled())) {
		return;
	}

	if (Q_UNLIKELY(columnAndOrder.size() != 2)) {
		return;
	}

	table->sortByColumn(columnAndOrder.at(COL_POS),
	   (columnAndOrder.at(SORT_POS) == ASCENDING_VAL) ? Qt::AscendingOrder : Qt::DescendingOrder);
}
