#include"sslcertdlg.h"

#include<qtextbrowser.h>
#include<qdatetime.h>
#include<qlabel.h>
#include<qpushbutton.h>
#include<qdict.h>
#include<qca.h>
#include"common.h"
#include"iconwidget.h"

static void setLabelStatus(QLabel *l, bool ok)
{
	if(ok)
		l->setPaletteForegroundColor(QColor("#2A993B"));
	else
		l->setPaletteForegroundColor(QColor("#810000"));
}

static QString getPropValue(const QCA::CertProperties &list, const QString &var)
{
	QString val;
	for(QCA::CertProperties::ConstIterator it = list.begin(); it != list.end(); ++it) {
		if(it.key() == var) {
			if(!val.isEmpty())
				val += "<br>";
			val += it.data();
		}
	}
	return val;
}

static QString makePropEntry(const QString &var, const QString &name, const QCA::CertProperties &list)
{
	QString val = getPropValue(list, var);
	if(val.isEmpty())
		return "";
	else
		return QString("<tr><td><nobr><b>") + name + "</b></nobr></td><td>" + val + "</td></tr>";
}

QString SSLCertDlg::makePropTable(const QString &heading, const QCA::CertProperties &list)
{
	QString str;
	str += "<tr><td><i>" + heading + "</i><br>";
	str += "<table>";
	str += makePropEntry("O", tr("Organization:"), list);
	str += makePropEntry("OU", tr("Organizational unit:"), list);
	str += makePropEntry("L", tr("Locality:"), list);
	str += makePropEntry("ST", tr("State:"), list);
	str += makePropEntry("C", tr("Country:"), list);
	str += makePropEntry("CN", tr("Common name:"), list);
	str += makePropEntry("Email", tr("Email:"), list);
	str += "</table></td></tr>";
	return str;
}

SSLCertDlg::SSLCertDlg(QWidget *parent, const char *name)
:SSLCertUI(parent, name, true)
{
	setCaption(CAP(caption()));

	connect(pb_close, SIGNAL(clicked()), SLOT(close()));
	pb_close->setDefault(true);
	pb_close->setFocus();
}

void SSLCertDlg::setCert(const QCA::Cert &cert, int result)
{
	if(cert.isNull())
		return;

	if(result == QCA::TLS::Valid) {
		lb_valid->setText(tr("The certificate is valid."));
		setLabelStatus(lb_valid, true);
	}
	else {
		lb_valid->setText(tr("The certificate is NOT valid!"));
		setLabelStatus(lb_valid, false);
	}

	QDateTime now = QDateTime::currentDateTime();
	QDateTime notBefore = cert.notBefore();
	QDateTime notAfter = cert.notAfter();
	lb_notBefore->setText(cert.notBefore().toString());
	setLabelStatus(lb_notBefore, now > notBefore);
	lb_notAfter->setText(cert.notAfter().toString());
	setLabelStatus(lb_notAfter, now < notAfter);

	lb_sn->setText(cert.serialNumber());

	QString str;
	str += "<table>";
	str += makePropTable(tr("Subject Details:"), cert.subject());
	str += makePropTable(tr("Issuer Details:"), cert.issuer());
	str += "</table>";
	tb_cert->setText(str);
}

void SSLCertDlg::showCert(const QCA::Cert &cert, int result)
{
	SSLCertDlg *w = new SSLCertDlg(0);
	w->setCert(cert, result);
	w->exec();
	delete w;
}
