/*
    SPDX-FileCopyrightText: 2010 Volker Lanz <vl@fidra.de>
    SPDX-FileCopyrightText: 2014-2017 Andrius Štikonas <andrius@stikonas.eu>

    SPDX-License-Identifier: GPL-3.0-or-later
*/

#include "util/htmlreport.h"

#include "backend/corebackend.h"
#include "backend/corebackendmanager.h"

#include <QApplication>
#include <QDateTime>
#include <QString>
#include <QTextStream>
#include <QTextDocument>

#include <KAboutData>
#include <KLocalizedString>
#include <ki18n_version.h>

#include <sys/utsname.h>

QString HtmlReport::tableLine(const QString& label, const QString contents)
{
    QString rval;
    QTextStream s(&rval);

    s << "<tr>\n"
      << QStringLiteral("<td style='font-weight:bold;padding-right:20px;'>%1</td>\n").arg(QString(label).toHtmlEscaped())
      << QStringLiteral("<td>%1</td>\n").arg(QString(contents).toHtmlEscaped())
      << "</tr>\n";

    s.flush();

    return rval;
}

QString HtmlReport::header()
{
    QString rval;
    QTextStream s(&rval);

    s <<
      "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
      "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
      "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
      "<head>\n"
      "	<title>"
      << i18n("%1: SMART Status Report", QGuiApplication::applicationDisplayName().toHtmlEscaped())
      << "</title>\n"
      "	<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>\n"
      "</head>\n\n"
      "<body>\n";

    s << "<h1>"
      << i18n("%1: SMART Status Report", QGuiApplication::applicationDisplayName().toHtmlEscaped())
      << "</h1>\n\n";

    struct utsname info;
    uname(&info);
    const QString unameString = QString::fromLocal8Bit(info.sysname) + QStringLiteral(" ") + QString::fromLocal8Bit(info.nodename) + QStringLiteral(" ") + QString::fromLocal8Bit(info.release) + QStringLiteral(" ") + QString::fromLocal8Bit(info.version) + QStringLiteral(" ") + QString::fromLocal8Bit(info.machine);

    s << "<table>\n"
      << tableLine(i18n("Date:"), QLocale().toString(QDateTime::currentDateTime(), QLocale::ShortFormat))
      << tableLine(i18n("Program version:"), QCoreApplication::applicationVersion())
      << tableLine(i18n("Backend:"), QStringLiteral("%1 (%2)").arg(CoreBackendManager::self()->backend()->id()).arg(CoreBackendManager::self()->backend()->version()))
      << tableLine(i18n("KDE Frameworks version:"), QStringLiteral(KI18N_VERSION_STRING))
      << tableLine(i18n("Machine:"), unameString)
      << "</table>\n<br/>\n";

    s << "<table>\n";

    s.flush();

    return rval;
}

QString HtmlReport::footer()
{
    return QStringLiteral("\n\n</body>\n</html>\n");
}
