#include "aboutwindow.h"

#include "qad_types.h"
#include "qpiconfig.h"
#include "ui_aboutwindow.h"

#include <QApplication>
#include <QFile>
#if QT_VERSION < 0x050000
#  include <QDesktopWidget>
#else
#  include <QScreen>
#endif

#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
#  define MOBILE_VIEW
#endif

QImage AboutWindow::logo;
QVector<AboutWindow::SSPair> AboutWindow::versions, AboutWindow::builds;
QString AboutWindow::comment, AboutWindow::stylesheet;


AboutWindow::AboutWindow(QWidget * parent): QDialog(parent), ui(new Ui::AboutWindow) {
#ifdef ANDROID
	QDialog::setStyleSheet("font: 12pt \"DejaVu Sans\";");
#endif
	if (!stylesheet.isEmpty()) QDialog::setStyleSheet(stylesheet);
	ui->setupUi(this);
	ui->labelAuthors->setOpenExternalLinks(true);
	QImage logo_im = logo;
	if (logo_im.isNull()) logo_im.load(":/icons/splash.png");
	setWindowTitle(QApplication::applicationName() + " - " + tr("About"));
	QIcon ic = QApplication::windowIcon();
	if (ic.isNull()) {
		QWidgetList tlw = QApplication::topLevelWidgets();
		foreach(QWidget * w, tlw)
			if (!w->windowIcon().isNull()) {
				ic = w->windowIcon();
				break;
			}
	}
	if (ic.isNull()) ic = QIcon(QPixmap::fromImage(logo_im));
	setWindowIcon(ic);
	QFormLayout * lay = (QFormLayout *)(ui->groupVersions->layout());
	foreach(SSPair p, versions) {
		lay->addRow(p.first, new QLabel(p.second));
	}
	lay = (QFormLayout *)(ui->groupBuild->layout());
	foreach(SSPair p, builds) {
		lay->addRow(p.first, new QLabel(p.second));
	}
	ui->imageView->setPixmap(QPixmap::fromImage(logo_im));
	ui->labelComment->setText(comment);
	ui->labelComment->setOpenExternalLinks(true);
	ui->labelComment->setHidden(comment.isEmpty());
	// ui->labelArch->setText(QSysInfo::currentCpuArchitecture());
	ui->labelAuthors->setText(authors());
	connect(ui->buttonQt, SIGNAL(clicked()), qApp, SLOT(aboutQt()));
#ifdef MOBILE_VIEW
	ui->layoutMain->insertWidget(0, ui->imageView);
	// ui->verticalSpacer->changeSize(1, 1, QSizePolicy::Preferred, QSizePolicy::Preferred);
#endif
#ifdef MOBILE_VIEW
	ui->layoutMain->addSpacerItem(new QSpacerItem(1, 1, QSizePolicy::Preferred, QSizePolicy::Expanding));
#else
	QRect r;
#  if QT_VERSION < 0x050000
	r = QApplication::desktop()->geometry();
#  else
	QScreen * scr =
#	if QT_VERSION >= 0x050A00
		QApplication::screenAt(QCursor::pos());
#	else
		QApplication::screens()[0];
#	endif
	if (scr) {
		r.setSize(scr->availableSize() / 2);
		r.moveCenter(scr->availableGeometry().center());
	}
#  endif
	if (r.isValid()) setGeometry(r);
#endif
}


AboutWindow::~AboutWindow() {
	delete ui;
}


void AboutWindow::setLogo(QImage im) {
	logo = im;
}


void AboutWindow::setLogo(QString path) {
	logo = QImage(path);
}


void AboutWindow::addVersion(QString name, QString version) {
	if (!name.endsWith(":")) name.append(":");
	foreach(const SSPair & p, versions) {
		if (p.first == name) return;
	}
	version.prepend("<b>");
	if (version.contains("("))
		version.insert(version.indexOf("("), "</b>");
	else
		version.append("</b>");
	versions << SSPair(name, version);
}


void AboutWindow::addBuildInfo(QString name, QString value) {
	if (!name.endsWith(":")) name.append(":");
	foreach(const SSPair & p, builds) {
		if (p.first == name) return;
	}
	builds << SSPair(name, value);
}


void AboutWindow::setComment(QString text) {
	comment = text;
}


void AboutWindow::setStyleSheet(QString ss) {
	stylesheet = ss;
}


void AboutWindow::show() {
	AboutWindow w;
	w.exec();
}


int AboutWindow::exec() {
#ifdef MOBILE_VIEW
	showFullScreen();
	// setWindowState(Qt::WindowFullScreen);
#endif
	return QDialog::exec();
}


void AboutWindow::changeEvent(QEvent * e) {
	QDialog::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		ui->retranslateUi(this);
		setWindowTitle(QApplication::applicationName() + " - " + tr("About"));
		break;
	case QEvent::FontChange:
	case QEvent::Polish:
		ui->buttonOK->setIconSize(preferredIconSize(2., this));
		ui->buttonQt->setIconSize(preferredIconSize(2., this));
		break;
	default: break;
	}
}


void addAuthor(QString & ret, const QString & name, const QString & mail) {
	if (mail.isEmpty())
		ret += QString("<p>%1</p>").arg(name);
	else
		ret += QString("<p>%1 (<a href=\"mailto:%2?subject=%3\">%2</a>)</p>").arg(name, mail, QApplication::applicationName());
}
QString AboutWindow::authors() {
	QString ret, fc;
	if (QFile::exists(":/authors.txt")) {
		QFile f(":/authors.txt");
		f.open(QIODevice::ReadOnly);
		fc = QString::fromUtf8(f.readAll());
	} else {
		if (QFile::exists(":/AUTHORS.txt")) {
			QFile f(":/AUTHORS.txt");
			f.open(QIODevice::ReadOnly);
			fc = QString::fromUtf8(f.readAll());
		}
	}
	QTextStream ts(&fc, QIODevice::ReadOnly);
	QString l = ts.readLine();
	if (l.contains(";")) {
		QStringList sl;
		while (!ts.atEnd()) {
			l = ts.readLine();
			if (l.isEmpty()) continue;
			QString name, mail;
			sl = l.split(";");
			if (sl.size() > 0) name = sl[0].trimmed();
			if (sl.size() > 1) mail = sl[1].trimmed();
			addAuthor(ret, name, mail);
		}
		return ret;
	} else {
		QPIConfig conf(&fc);
		QPIConfig::Branch br = conf.allLeaves();
		foreach(QPIConfig::Entry * e, br) {
			l = e->toString().trimmed();
			if (!l.contains("<")) continue;
			QString name, mail;
			name = l.left(l.indexOf("<"));
			mail = l.mid(name.size() + 1);
			if (mail.endsWith(">")) mail.chop(1);
			name = name.trimmed();
			mail = mail.trimmed();
			addAuthor(ret, name, mail);
		}
	}
	return ret;
}
