#include "SH_packages.h"
#include "SH_types.h"
#include "SH_server_base.h"
#include "SH_network_types.h"
#include <pifile.h>
#include <pidir.h>
#include <piqt.h>
#include <QApplication>
#include <QMetaEnum>


SHPackages::SHPackages() {
	dir_path = Q2PIString(QApplication::applicationDirPath()) + "/packages/Pult_remote/";
	reloadPackages();
}


SHPackages::~SHPackages() {
}


SHPackages * SHPackages::instance() {
	static SHPackages * ret = new SHPackages();
	return ret;
}


void SHPackages::reloadPackages() {
	packages.clear();
	PIString base = "SHS_Pult_" SHS_VERSION_NAME;
	PIVector<PIFile::FileInfo> fil = PIDir(dir_path).entries();
	piForeachC (PIFile::FileInfo & f, fil) {
		if (!f.isFile()) continue;
		if (!f.name().startsWith(base)) continue;
		PIString fn = f.name().mid(base.size_s() + 1);
		fn.cutRight(f.extension().size_s() + 1);
		PIString arch = fn.takeMid(fn.find("_") + 1);
		PIString os = fn.cutRight(1);
		Package & p(packages[hostType(OSByName(os), arch)]);
		p.name = f.name();
		PIFile file(f.path, PIIODevice::ReadOnly);
		if (file.open())
			p.file = f.path;
		piCout << "Found package for" << os << arch << "(" << PIString::readableSize(file.size()) << ")";
	}
}


PIString SHPackages::packageNameForHost(const PIString & host_type) const {
	return packages.value(host_type).name;
}


PIString SHPackages::genPackageNameForHost(int os_type, const PIString & arch) const {
	QMetaEnum ose = SHPlatform::staticMetaObject.enumerator(SHPlatform::staticMetaObject.indexOfEnumerator("OSType"));
	QString osn = QString(ose.valueToKey(os_type));
	if (osn == "MacOS") osn = "Darwin";
	return "SHS_Pult_" SHS_VERSION_NAME "_" + Q2PIString(osn) + "_" + arch;
}


SHPackages::Package SHPackages::packageForHost(const PIString & host_type) const {
	return packages.value(host_type);
}


void SHPackages::loadPackageForHost(const PIString & host_type) {
	Package & p(packages[host_type]);
	if (p.file.isEmpty() || !p.data.isEmpty()) return;
	PIFile file(p.file, PIIODevice::ReadOnly);
	if (file.open())
		p.data = file.readAll();
}
