/*
 *  Copyright (C) 2007-2008 CMM Sigma Andrzej Chmielowiec <cmmsigma@cmmsigma.eu>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#include "GenCertReqWidget.h"
#include "FileDialogWPR.h"
#include "MainWindow.h"

#ifndef NO_MAIL
#include "AdminOptions.h"
#endif

QLineEditFiltered::QLineEditFiltered(QWidget *parent) : QLineEdit(parent)
{
	connect(this, SIGNAL(textChanged(const QString&)), this, 
		SLOT(textCheck(const QString&)));
}

void
QLineEditFiltered::textCheck(const QString &name)
{
	foreach (QChar c, name)
	{
		if ((c < 'a' || c > 'z') 
			&& (c < 'A' || c > 'Z') 
			&& (c < '0' || c > '9') 
			&& c != '-' && c != '_'
			&& c != ' ')
		{
			QMessageBox::information(this, tr("Incorrect data"), 
				tr("This field can store alphanumeric characters "
				"[a-z][A-Z][0-9], '_', '-' and ' ' only."));
			setText(mCorrectText);
		}
	}
	
	mCorrectText = text();
}


GenCertReqWidget::GenCertReqWidget(QWidget *parent): QWidget(parent)
{
	mCountryCode = new QLineEdit;
	mCountryCode->setMaxLength(2);
	mStateOrProvinceName = new QLineEditFiltered();
	mLocalityName = new QLineEditFiltered();
	mOrganizationName = new QLineEditFiltered();
	mOrganizationalUnitName = new QLineEditFiltered();
	mCommonName = new QLineEditFiltered();
	mEmailAddress = new QLineEdit();
	mGenerate = new QPushButton(QIcon(QString(":img/filetype_userreq.png")), 
		tr("Generate"));
	
	QGridLayout *layout = new QGridLayout;
	layout->addWidget(new QLabel(tr("Country code:")), 0, 0);
	layout->addWidget(mCountryCode, 0, 1, 1, 3);
	layout->addWidget(new QLabel(tr("Region:")), 1, 0);
	layout->addWidget(mStateOrProvinceName, 1, 1, 1, 3);
	layout->addWidget(new QLabel(tr("City:")), 2, 0);
	layout->addWidget(mLocalityName, 2, 1, 1, 3);
	layout->addWidget(new QLabel(tr("Organization:")), 3, 0);
	layout->addWidget(mOrganizationName, 3, 1, 1, 3);
	layout->addWidget(new QLabel(tr("Department:")), 4, 0);
	layout->addWidget(mOrganizationalUnitName, 4, 1, 1, 3);
	layout->addWidget(new QLabel(tr("Common name:")), 5, 0);
	layout->addWidget(mCommonName, 5, 1, 1, 3);
	layout->addWidget(new QLabel(tr("E-mail:")), 6, 0);
	layout->addWidget(mEmailAddress, 6, 1, 1, 3);
	layout->addWidget(mGenerate, 7, 3);
	
	layout->setRowStretch(8, 1);
	layout->setColumnStretch(1, 1);
	layout->setColumnStretch(2, 6);
	
	connect(mGenerate, SIGNAL(clicked()), this, SLOT(generateCertReqSlot()));
	
	setLayout(layout);
	disable();
}

void
GenCertReqWidget::enable()
{
	setEnabled(true);
}

void
GenCertReqWidget::disable()
{
	setEnabled(false);
}

void
GenCertReqWidget::generateCertReqSlot()
{
	QStringList dn;
	
	dn << QString("countryName=").append(mCountryCode->text());
	
	if (mStateOrProvinceName->text() != QString())
		dn << QString("stateOrProvinceName=").append(mStateOrProvinceName->text());
	
	if (mLocalityName->text() != QString())
		dn << QString("localityName=").append(mLocalityName->text());
	
	if (mOrganizationName->text() != QString())
		dn << QString("organizationName=").append(mOrganizationName->text());
	
	if (mOrganizationalUnitName->text() != QString())
		dn << QString("organizationalUnitName=").append(mOrganizationalUnitName->text());
	
	if (mCommonName->text() != QString())
		dn << QString("commonName=").append(mCommonName->text());
	
	if (mEmailAddress->text() != QString())
		dn << QString("emailAddress=").append(mEmailAddress->text());

	QWidget *top = this;
	while (top->parentWidget() != 0)
		top = top->parentWidget();

	QString commonName = mCommonName->text().replace(' ', '_');
	if(commonName.isEmpty())
		commonName = tr("request");
	commonName += ".req";

	QString fileName, mail;
	bool send = false;

#ifndef NO_MAIL
	MainWindow *wnd = static_cast<MainWindow *>(top);
	AdminOptions *config = wnd->getConfig();
	send = config->mailConfig.mUseMail;

	if(send)
	{
		int button = QMessageBox::question(this, tr("Question"), tr("Send request to CA now?"), QMessageBox::Yes | QMessageBox::No, 
			QMessageBox::Yes);
	
		if(button == QMessageBox::No)
			send = false;
		else
		{
			bool ok = true;
			while(mail.isEmpty() && ok)
			{
				mail = QInputDialog::getText(this, tr("Enter CA's e-mail address"),
					tr("CA's e-mail address:"), QLineEdit::Normal, QString(), &ok);
			}
		}

		if(!mail.isEmpty())
			fileName = QDir::tempPath() + QDir::separator() + commonName;
	}
#endif

	if(!send)
	{
		fileName = FileDialogWPR::getSaveFileName(this, tr("Save as"),
			QDir::homePath() + QDir::separator() + commonName,
			tr("Requests (*.req);;All files (*)"));
	}
	
	top->repaint();
	
	if (!fileName.isEmpty())
	{
		emit generateCertReqSig(fileName, dn, mail);
	
		mStateOrProvinceName->clear();
		mLocalityName->clear();
		mOrganizationName->clear();
		mOrganizationalUnitName->clear();
		mCommonName->clear();
		mEmailAddress->clear();
	}
}
