#include "microsoftoffice.h"

#include <QDebug>
#include <QProcess>
#include <QDir>
#include <QFileInfo>

#include "genuine.h"

namespace Win
{

void MicrosoftOffice::updateStatus(Software &s)
{
    auto osppRelPath = QStringLiteral("");
    auto regPath = QStringLiteral("");
    if (s.DisplayName.contains("2003")) {
        regPath = QStringLiteral("SOFTWARE\\Microsoft\\Office\\11.0\\Registration\\{90110804-6000-11D3-8CFE-0150048383C9}");
    }
    if (s.DisplayName.contains("2007")) {
        regPath = QStringLiteral("SOFTWARE\\Microsoft\\Office\\12.0\\Registration\\{90120000-0014-0000-0000-0000000FF1CE}");
    }
    if (s.DisplayName.contains("2010")) {
        regPath = QStringLiteral("SOFTWARE\\Microsoft\\Office\\14.0\\Registration\\{91140000-0011-0000-0000-0000000FF1CE}");
        osppRelPath = QStringLiteral("Office14/OSPP.VBS");
    }
    if (s.DisplayName.contains("2013")) {
        osppRelPath = QStringLiteral("Office15/OSPP.VBS");
        regPath =   QStringLiteral("SOFTWARE\\Microsoft\\Office\\15.0\\Registration\\{90150000-0011-0000-1000-0000000FF1CE}");
    }
    if (s.DisplayName.contains("2016")) {
        osppRelPath = QStringLiteral("Office16/OSPP.VBS");
    }

    QDir installDir(s.InstallLocation);
    auto osppPath = installDir.absoluteFilePath(osppRelPath);

    qDebug() << regPath << osppRelPath << s.InstallLocation << osppPath;

    if (QFile::exists(osppPath)) {
        QProcess osppApp;
        osppApp.setProgram("cscript");
        osppApp.setArguments({osppPath, "/dstatus"});

        osppApp.start();
        osppApp.waitForStarted();
        osppApp.waitForFinished(60 * 1000);

        auto output = QString::fromLocal8Bit(osppApp.readAll());

        qDebug() << osppApp.program() << osppApp.arguments();
        qDebug() << output.toLocal8Bit();
        qDebug() << osppApp.exitCode()
                 << osppApp.exitStatus()
                 << osppApp.readAllStandardError();

        auto statusKey = QStringLiteral("LICENSE STATUS:");
        for (QString &line : output.split("\r\n")) {
            if (line.startsWith(statusKey)) {
                auto status = line.remove(statusKey).trimmed();
                qDebug() << status;
                if (status == QStringLiteral("---LICENSED---")) {
                    qDebug() << "active";
                    s.IsGenuine = true;
                } else {
                    qDebug() << "no";
                    s.IsGenuine = false;
                }
            }
        }
    } else {
        qDebug() << osppPath << "not installed";
    }

    //GetSerialKey
    if (!regPath.isEmpty()) {
        s.ProductKeys = QStringList{ Genuine::GetKey(regPath) };
    }
}

}
