#include "stdafx.h"
#include "QGVAboutDlg.h"

#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>
#include <QDomDocument>
#include <QDir>

#include <Qt5Utility/QXmlExt.h>

#include "BuildInfo.h"
#include "DownloadManager.h"
#include "AppVersion.h"
#include "PathInfo.h"

#include "../../Lib/Qt5Utility/ExtCmdRunner.h"



static const char* PROJECT_URL = "https://osdn.jp/projects/qtgeoviewer/";
static const char* RELEASE_RSS = "https://osdn.jp/projects/qtgeoviewer/releases/rss";


QGVAboutDlg::QGVAboutDlg(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	Qt::WindowFlags flags = windowFlags() & (~Qt::WindowContextHelpButtonHint);
	flags = flags | Qt::WindowCloseButtonHint;
	setWindowFlags(flags);

	std::string info = GetInfo();
	ui.textMain->document()->setPlainText(QString::fromLocal8Bit(info.c_str()));
}

QGVAboutDlg::~QGVAboutDlg()
{
}

std::string QGVAboutDlg::GetInfo(void)
{
	std::ostringstream ss;
	ss << "VERSION : " << VERSION_MAJOR << "." << VERSION_MINOR << "." << BUILD_NUMBER << "." << VCS_REVISION << std::endl;
	ss << "BUILD_ID : " << BUILD_ID << std::endl;
	ss << "SOURCE_HASH : " << SOURCE_HASH << std::endl;
	ss << std::endl;
	ss << "Project URL : " << std::endl;
	ss << "  " << PROJECT_URL << std::endl;

	return ss.str();
}

void QGVAboutDlg::on_buttonBox_accepted()
{
	close();
}

void QGVAboutDlg::on_commandOpenProjectPage_clicked()
{
	ShowProjectPage();
}

void QGVAboutDlg::ShowProjectPage(void)
{
	QDesktopServices::openUrl(QUrl(PROJECT_URL));
}

void QGVAboutDlg::on_commandCheckUpdate_clicked()
{
	AppVersion latest;
	QString latest_vs;
	if (!GetVersionFromWeb(latest, latest_vs))
	{
		QMessageBox::information(this, "", tr("Failed to get version info"));
		return;
	}

	AppVersion my_version = AppVersion::GetCurrent();

	if (my_version < latest)
	{
		QString msg = tr("Exist new version.\n Click \"Yes\" to go to project page.");
		if (QMessageBox::information(this, "", msg, QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
		{
			ShowProjectPage();
		}
	}
	else
	{
		QMessageBox::information(this, "", tr("Current version is latest."));
	}
}

bool QGVAboutDlg::GetVersionFromWeb(AppVersion& version, QString& vs)
{
	if (!GetVersionTextFromWeb(vs))
		return false;

	return version.FromDotSplit(vs);
}

bool QGVAboutDlg::GetVersionTextFromWeb(QString& version)
{
	if (!DownloadReleaseRSS())
		return false;

	QFile file(GetTmpPath());
	if (!file.open(QIODevice::ReadOnly))
		return false;

	QDomDocument xml;
	xml.setContent(&file);

	bool suc = ReadXmlBuf(xml, version);
	file.close();
	return suc;
}

bool QGVAboutDlg::ReadXmlBuf(QDomDocument& xml, QString& version)
{
	QXML_ELEM_FOREACH(n_rss, xml)
	{
		QXML_ELEM_FOREACH(n_channel, n_rss)
		{
			QXML_ELEM_FOREACH(n_item, n_channel)
			{
				if (n_item.nodeName() == "item")
				{
					QXML_ELEM_FOREACH(n_title, n_item)
					{
						QString nn = n_title.nodeName();
						if (n_title.nodeName() == "title")
						{
							QString release_name = n_title.firstChild().nodeValue();
							int spl = release_name.indexOf(" - ");
							if (spl == -1)
								return false;

							version = release_name.mid(spl + 3);

							return true;
						}
					}
					break;
				}
			}
			break;
		}
		break;
	}

	return false;
}

QString QGVAboutDlg::GetTmpPath(void)
{
	QString dst = PathInfo::GetAppTmpPath();
	dst = QDir::toNativeSeparators(dst);
	dst += "version.xml";
	return dst;
}

bool QGVAboutDlg::DownloadReleaseRSS(void)
{
	QString url = RELEASE_RSS;
	QString dst = GetTmpPath();

	QString tmp_dir = PathInfo::GetAppTmpPath();
	if (!QDir().exists(tmp_dir))
		QDir().mkpath(tmp_dir);

	if (QFile(dst).exists())
		QFile::remove(dst);

	ExtCmdRunner runner;
	runner.cmd = PathInfo::GetWebDownloaderPath();
	runner.args = "";
	runner.args += url;
	runner.args += " ";
	runner.args += dst;

	runner.Execute2(ShellExecMode::Wait);

	if (!QFile(dst).exists())
		return false;

	return true;
}
