#include "commandlinepackagedb.h"
#include "aptcacheparser.h"
#include "dpkgparser.h"
#include "helpers.h"
#include "iprogressobserver.h"
#include "aptpackagebuilder.h"

#include "packagenotfoundexception.h"

namespace NApt {

/** Adds the packages from */
void mergeWithDpkgPackages(
    map<QString, unique_ptr<const IPackage>>& target,
    const map<string, const DpkgParser::PackageInformation>& dpkgPackages
) {
    for (auto const& [name, dpkgPackage] : dpkgPackages)
    {
        QString qName = toQString(name);
        if (target.find(qName) == target.end()) {
            AptPackageBuilder builder;
            builder.setName(qName);
            builder.setVersion(toQString(dpkgPackage.version));
            builder.setDescription(toQString(dpkgPackage.description));
            builder.setArchitecture(toQString(dpkgPackage.architecture));
            target[qName] = builder.createPackage();
        }
    }
}

map<QString, unique_ptr<const IPackage>> getPackages(
    const NPlugin::IProvider& provider,
    NUtil::IProgressObserver& observer
) {
    auto dpkgPackages = DpkgParser::getInstalledPackages();
    auto aptPackages = AptCacheParser::parseDumpAvail(provider.packages().size(), dpkgPackages, observer);
    mergeWithDpkgPackages(aptPackages, dpkgPackages);
    return aptPackages;
}

CommandLinePackageDB::CommandLinePackageDB(
    const NPlugin::IProvider& provider,
    NUtil::IProgressObserver& observer
    ) : _packages(getPackages(provider, observer)) {
}

const IPackage& CommandLinePackageDB::getPackageRecord(const QString &pkg) const {
    auto resultIterator = _packages.find(pkg);
    if (resultIterator == _packages.end()) {
        throw NPlugin::PackageNotFoundException(pkg.toStdString());
    }
    return *(resultIterator->second);
}

PackageDetails CommandLinePackageDB::getPackageDetails(const string& name) const {
    return AptCacheParser::parseCacheShow(name);
}

const IPackage& CommandLinePackageDB::getPackageRecord(const string &package) const {
    return getPackageRecord(toQString(package));
}

const QString CommandLinePackageDB::getShortDescription(const string &package) const {
    return getPackageRecord(package).shortDescription();
}

IPackage::InstalledState CommandLinePackageDB::getState(const string &package) const {
    return getPackageRecord(package).installedState();
}

void CommandLinePackageDB::reloadPackageInformation(NUtil::IProgressObserver *pObserver) {
    pObserver->setProgress(100);
}

}
