/*
 *  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.
 */

// FTPAccountWidget.cpp: implementation of the FTPAccountWidget class.
//
//////////////////////////////////////////////////////////////////////

#include "FTPAccountWidget.h"
#include <QInputDialog>

QFTPTableWidgetItem::QFTPTableWidgetItem(const QString &text)
{
	setText(text);
}

FTPAccountWidget::FTPAccountWidget(QWidget *parent) : QWidget(parent)
{
	mCurr = 0;

	QGridLayout *left = new QGridLayout();
	QGridLayout *right = new QGridLayout();

	QSplitter *splitter = new QSplitter();
	QWidget *wleft = new QWidget();
	QGroupBox *wright = new QGroupBox(tr("FTP server"));
	splitter->addWidget(wleft);
	splitter->addWidget(wright);
	
	QList<int> sizes;
	sizes.append(400);
	sizes.append(500);
	splitter->setSizes(sizes);

	wleft->setLayout(left);
	wright->setLayout(right);

	mAddAccount = new QPushButton(QIcon(QString(":img/add.png")), tr("Add account"));
	mDelAccount = new QPushButton(QIcon(QString(":img/cancel.png")), tr("Delete account"));
	
	mServers = new QTableWidget();
	left->addWidget(mServers, 0, 0);

	QGridLayout *b1 = new QGridLayout();
	left->addLayout(b1, 1, 0);

	b1->addWidget(mAddAccount, 0, 0);
	b1->addWidget(mDelAccount, 0, 1);
	b1->setColumnStretch(2, 1);

	mServer = new QLineEdit();
	mUser = new QLineEdit();
	mPass = new QLineEdit();
	mPass->setEchoMode(QLineEdit::Password);

	right->addWidget(new QLabel(tr("Server address")), 0, 0);
	right->addWidget(mServer, 0, 1);
	right->addWidget(new QLabel(tr("User")), 1, 0);
	right->addWidget(mUser, 1, 1);
	right->addWidget(new QLabel(tr("Password")), 2, 0);
	right->addWidget(mPass, 2, 1);

	mUseAccount = new QCheckBox(tr("Use this account when distributing CRL list"));
	right->addWidget(mUseAccount, 3, 0, 1, 2);
	
	mPaths = new QTableWidget();
	right->addWidget(new QLabel(), 4, 0, 1, 2);
	right->addWidget(mPaths, 5, 0, 1, 2);

	QGridLayout *b2 = new QGridLayout();
	right->addLayout(b2, 6, 0, 1, 2);

	mAddPath = new QPushButton(QIcon(QString(":img/add.png")), tr("Add"));
	mDelPath = new QPushButton(QIcon(QString(":img/cancel.png")), tr("Delete"));

	b2->addWidget(mAddPath, 0, 0);
	b2->addWidget(mDelPath, 0, 1);
	b2->setColumnStretch(2, 1);

	QGridLayout *layout = new QGridLayout();
	layout->addWidget(splitter, 0, 0);

	setLayout(layout);

	connect(mAddAccount, SIGNAL(clicked()), this, SLOT(addAccount()));
	connect(mDelAccount, SIGNAL(clicked()), this, SLOT(delAccount()));
	connect(mAddPath, SIGNAL(clicked()), this, SLOT(addPath()));
	connect(mDelPath, SIGNAL(clicked()), this, SLOT(delPath()));
	
	connect(mServer, SIGNAL(editingFinished()), this, SLOT(addressFinished()));

	connect(mServers, SIGNAL(currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
		this, SLOT(serverItemChanged(QTableWidgetItem *, QTableWidgetItem *)));

	mServers->setSelectionMode(QAbstractItemView::SingleSelection);
	mServers->setSelectionBehavior(QAbstractItemView::SelectRows);
	mServers->setEditTriggers(QAbstractItemView::DoubleClicked
		| QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed);
	QStringList labels1;
	labels1 << tr("FTP servers");
	mServers->setColumnCount(1);
	mServers->setHorizontalHeaderLabels(labels1);
	mServers->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);

	mPaths->setSelectionMode(QAbstractItemView::SingleSelection);
	mPaths->setSelectionBehavior(QAbstractItemView::SelectRows);
	mPaths->setEditTriggers(QAbstractItemView::DoubleClicked
		| QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed);
	QStringList labels2;
	labels2 << tr("CRL file paths");
	mPaths->setColumnCount(1);
	mPaths->setHorizontalHeaderLabels(labels2);
	mPaths->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
}

FTPAccountWidget::~FTPAccountWidget()
{
}

// slots
void
FTPAccountWidget::addAccount()
{
	mCurr = new QFTPTableWidgetItem();
	mCurr->mName = mCurr->text();

	int row = mServers->currentRow() + 1;
	if(row < 0)
		row = mServers->rowCount();

	mServers->insertRow(row);
	mServers->setItem(row, 0, mCurr);
	mServers->setCurrentItem(mCurr);

	updateFTPPanel();
	mServer->setFocus();
}

void
FTPAccountWidget::delAccount()
{
	if(mCurr == 0)
		return;

	int button = QMessageBox::question(this, tr("Question"), tr("Do you want to delete selected FTP account?"), QMessageBox::Yes | QMessageBox::No, 
		QMessageBox::No);
	
	if(button == QMessageBox::Yes)
	{
		int row = mServers->currentRow();
		mServers->removeRow(row);

		if(mServers->rowCount() == 0)
		{
			mCurr = 0;

			mServer->clear();
			mUser->clear();
			mPass->clear();
			mUseAccount->setCheckState(Qt::Unchecked);

			while(mPaths->rowCount() > 0)
				mPaths->removeRow(0);
		}
	}

	updateFTPPanel();
}

void
FTPAccountWidget::addPath()
{
	int row = mPaths->currentRow() + 1;
	if(row < 0)
		row = mPaths->rowCount();

	mPaths->insertRow(row);
	QTableWidgetItem *item = new QTableWidgetItem();
	mPaths->setItem(row, 0, item);
	mPaths->setCurrentItem(item);
}

void
FTPAccountWidget::delPath()
{
	int row = mPaths->currentRow();
	mPaths->removeRow(row);
}

void
FTPAccountWidget::saveData(QTableWidgetItem *previous)
{
	if(previous != 0)
	{
		QFTPTableWidgetItem *prev = static_cast<QFTPTableWidgetItem *>(previous);	
        
		if(prev->text().isEmpty())
		{
			prev->setText(mServer->text());
		}

		prev->mName = prev->text();
		prev->mServer = mServer->text();
		prev->mUser = mUser->text();
		prev->mPass = mPass->text();
		prev->mUseAccount = mUseAccount->checkState() == Qt::Checked ? true : false;

		prev->mPaths.clear();
		for(int i=0; i<mPaths->rowCount(); i++)
		{
			QTableWidgetItem *item = mPaths->item(i, 0);
			QString path = item->text();
			if(!path.isEmpty())
			{
				path = path.replace('\\', '/');
				
				QStringList names = path.split('/', QString::SkipEmptyParts);
				path.clear();
				for(int j=0; j<names.size(); j++)
				{
					if(j > 0)
						path += '/';
					path += names[j];
				}

				prev->mPaths.append(path);
			}
		}
	}
}

void
FTPAccountWidget::serverItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
{
	saveData(previous);

	mCurr = static_cast<QFTPTableWidgetItem *>(current);

	if(mCurr != 0)
	{
		mServer->setText(mCurr->mServer);
		mUser->setText(mCurr->mUser);
		mPass->setText(mCurr->mPass);
		mUseAccount->setCheckState(mCurr->mUseAccount ? Qt::Checked : Qt::Unchecked);

		while(mPaths->rowCount() > 0)
			mPaths->removeRow(0);

		for(int i=0; i<mCurr->mPaths.count(); i++)
		{
			mPaths->insertRow(i);
			QTableWidgetItem *item = new QTableWidgetItem(mCurr->mPaths[i]);
			mPaths->setItem(i, 0, item);
		}
	}
}

void
FTPAccountWidget::setData(CaOptions::FTPConfig &data)
{
	while(mServers->rowCount() > 0)
		mServers->removeRow(0);

	while(mPaths->rowCount() > 0)
		mPaths->removeRow(0);

	int row = 0;
	foreach(CaOptions::FTPConfig::FTPAccount acc, data.mAccounts)
	{
		QFTPTableWidgetItem *item = new QFTPTableWidgetItem(acc.mName);

		item->mName = acc.mName;
		item->mServer = acc.mServer;
		item->mUser = acc.mUser;
		item->mPass = acc.mPass;
		item->mUseAccount = acc.mUseAccount;

		foreach(QString path, acc.mPaths)
		{
			item->mPaths.append(path);
		}

		mServers->insertRow(row);
		mServers->setItem(row, 0, item);

		mCurr = item;

		row ++;
	}

	if(mServers->rowCount() > 0)
		mServers->setCurrentItem(mServers->item(0, 0));

	updateFTPPanel();
}

void
FTPAccountWidget::getData(CaOptions::FTPConfig &data)
{
	data.mAccounts.clear();

	saveData(mServers->currentItem());

	for(int i=0; i<mServers->rowCount(); i++)
	{
		QFTPTableWidgetItem *item = static_cast<QFTPTableWidgetItem *>(mServers->item(i, 0));

		CaOptions::FTPConfig::FTPAccount acc;
		acc.mName = item->mName;
		acc.mServer = item->mServer;
		acc.mUser = item->mUser;
		acc.mPass = item->mPass;
		acc.mUseAccount = item->mUseAccount;

		foreach(QString path, item->mPaths)
		{
			acc.mPaths.append(path);
		}

		data.mAccounts.append(acc);
	}
}

void
FTPAccountWidget::updateFTPPanel()
{
	bool on = mServers->rowCount() > 0 ? true : false;

	mServer->setEnabled(on);
	mUser->setEnabled(on);
	mPass->setEnabled(on);
	mUseAccount->setEnabled(on);
	mPaths->setEnabled(on);
	mAddPath->setEnabled(on);
	mDelPath->setEnabled(on);
}

void
FTPAccountWidget::addressFinished()
{
	int row = mServers->currentRow();
	if(row != -1)
	{
		QFTPTableWidgetItem *item = static_cast<QFTPTableWidgetItem *>(mServers->item(row, 0));

		if(item->text().isEmpty())
		{
			item->setText(mServer->text());
		}
	}
}
