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

#include "src/datovka_shared/io/matomo_reporter.h"
#include "src/datovka_shared/json/report.h"
#include "src/io/stats_reporter.h"
#include "tests/matomo_reporter_app/gui/app.h"

#define MATOMO_URL "http://localhost/matomo"
#define DFLT_INTERVAL_MS 125

#define SITE_ID 1
#define WEBAPP_NAME "matomo_test"

MainWindow::MainWindow(void)
    : QMainWindow(),
    m_timer(this),
    m_reporter(Q_NULLPTR)
{
	setupUi(this);

	connect(ui_intervalSpinBox, SIGNAL(valueChanged(int)),
	    this, SLOT(setTimerInterval(int)));

	ui_intervalSpinBox->setMinimum(0);
	ui_intervalSpinBox->setMaximum(3600000);
	ui_intervalSpinBox->setValue(DFLT_INTERVAL_MS);

	ui_splitter->setChildrenCollapsible(false);
	ui_textEdit->setReadOnly(true);
	ui_urlTextEdit->setReadOnly(true);

	connectTopMenuBarActions();

	m_reporter = new (::std::nothrow) MatomoReporter(this);
	if (Q_NULLPTR != m_reporter) {
		m_reporter->setTrackerUrl(QUrl(MATOMO_URL));
		m_reporter->setSiteId(SITE_ID);
		m_reporter->setWebAppName(WEBAPP_NAME);
		m_reporter->setUseRand(true);

		connect(m_reporter, SIGNAL(requestFinished(QUrl)),
		    this, SLOT(appendUrl(QUrl)));
	}

	connect(&m_timer, SIGNAL(timeout()), this, SLOT(runTracker()));
}

void MainWindow::runTracker(void)
{
	static int iteration = 0;

	if (Q_NULLPTR != m_reporter) {
		m_reporter->setUserId(QString("user_id_%1").arg(iteration));
		m_reporter->setClientId(QString("0123456789ABCDEF"));

		QString report;

		{
			Json::BuildReport buildReport;
			buildReport.setAppType(Json::Report::AT_TESTING);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
			buildReport.setUniqueId(StatsReporter::constructUniqueId());
#else
# error "Find a solution to get unique machine identifier."
#endif /* >= Qt-5.11 */

			QString jsonStr = buildReport.toJsonData();
			m_reporter->setCustomVisitVariables(
			    "testapp_build_report", StatsReporter::escapeQuotes(jsonStr));

			report += " " + jsonStr;
		}

		{
			Json::ConfReport confReport;
			confReport.setAppType(Json::Report::AT_TESTING);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
			confReport.setUniqueId(StatsReporter::constructUniqueId());
#else
# error "Find a solution to get unique machine identifier."
#endif /* >= Qt-5.11 */

			QString jsonStr = confReport.toJsonData();
			m_reporter->setCustomVisitVariables(
			    "testapp_conf_report", StatsReporter::escapeQuotes(jsonStr));

			report += " " + jsonStr;
		}

		{
			Json::UsageReport usageReport;
			usageReport.setAppType(Json::Report::AT_TESTING);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
			usageReport.setUniqueId(StatsReporter::constructUniqueId());
#else
# error "Find a solution to get unique machine identifier."
#endif /* >= Qt-5.11 */

			/* Set collected data. */
			usageReport.setNumBoxesProd(1);
			usageReport.setNumBoxesTesting(4);
			usageReport.setMessageDataSizeProd(1000000);
			usageReport.setMessageDataSizeTesting(16000000);
			usageReport.setNumDefinedTags(7);
			usageReport.setUsesDatabasesInMemory(false);
			usageReport.setUsesPin(true);
			usageReport.setUsesRecordsManagement(false);

			QString jsonStr = usageReport.toJsonData();
			m_reporter->setCustomVisitVariables(
			    "testapp_usage_report", StatsReporter::escapeQuotes(jsonStr));

			report += " " + jsonStr;
		}

		m_reporter->sendVisit(StatsReporter::constructVisitPath(Json::Report::AT_TESTING), "");

		ui_textEdit->append(QString("Iteration: %1; send '%2'")
		    .arg(iteration)
		    .arg(report));
	}

	++iteration;
}

void MainWindow::timerStart(void)
{
	ui_statusbar->showMessage("Running", 0);
	m_timer.start();
}

void MainWindow::timerStop(void)
{
	ui_statusbar->showMessage("Stopped", 0);
	m_timer.stop();
}

void MainWindow::setTimerInterval(int ms)
{
	m_timer.setInterval(ms);
}

void MainWindow::appendUrl(const QUrl &url)
{
	ui_urlTextEdit->append(QString("Processed: %1").arg(QString(url.toEncoded())));
}

void MainWindow::connectTopMenuBarActions(void)
{
	/* File menu. */
	connect(ui_actionQuit, SIGNAL(triggered()), this, SLOT(close()));

	/* Operations menu. */
	connect(ui_actionStartSending, SIGNAL(triggered()),
	    this, SLOT(timerStart()));
	connect(ui_actionStopSending, SIGNAL(triggered()),
	    this, SLOT(timerStop()));
}
