#include "OnlineProduct.h"

OnlineProduct::OnlineProduct()
{
	pDocument = new TiXmlDocument();

}
OnlineProduct::~OnlineProduct()
{
	delete pDocument;
	pDocument = nullptr;
}

const char* OnlineProduct::GetInstallPageVersion(wstring productUrl)
{
	//下载xml文件
	wstring SaveFolder = FolderCore::GetOrCreateFolderPath(PathCore::smPath_Temp) + L"/" + L"test.xml";
	HRESULT Hfile = URLDownloadToFile(NULL, productUrl.c_str(), SaveFolder.c_str(), 0, NULL);

	char* pStr = CharConvert::GetMultiByteW(SaveFolder.c_str());

	return LoadXmlA(pStr);
}


const char* OnlineProduct::LoadXmlA(const char* xmlStr)
{
	//加载xml文件
	if (pDocument == NULL)
		pDocument = new TiXmlDocument();

	if (!pDocument->LoadFile(xmlStr, TIXML_ENCODING_UNKNOWN))
	{
		return "";
	}

	
	return GetVersionFromXmlA();
}

const char* OnlineProduct::GetVersionFromXmlA()
{
	//解析xml
	TiXmlElement* pRootElement = pDocument->RootElement();
	if (NULL == pRootElement)
	{
		return "";
	}

	TiXmlElement* xml_host = pRootElement->FirstChildElement("channel");
	if (xml_host == pRootElement || xml_host == NULL)
	{
		return "";
	}

	TiXmlElement* item = xml_host->FirstChildElement("item");
	if (item == NULL)
	{
		return "";
	}

	TiXmlElement* enclosure = item->FirstChildElement("enclosure");
	if (enclosure == NULL)
	{
		return "";
	}

	const char* URI = enclosure->Attribute("url");
	if (URI == NULL)
	{
		return "";
	}
	Product::URI_InstallPackge = std::wstring(URI, URI + strlen(URI));

	const char* version = enclosure->Attribute("sparkle:version");
	if (version == NULL)
	{
		return "";
	}
	m_Verstion = version;
	return version;
}


wstring OnlineProduct::GetVersionW()
{
	return CharConvert::GetWideCharW(&m_Verstion);
}
