/***************************************************************************
 *   Copyright (C) 2007 by Michael Zanetti   
 *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   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.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif

#include <tqlayout.h>
#include <tqlabel.h>
#include <tqmap.h>
#include <tqptrlist.h>
#include <tqcombobox.h>
#include <tqstringlist.h>
#include <tqtable.h>
#include <tqpaintdevicemetrics.h>
#include <tqvbox.h>
#include <tqradiobutton.h>
#include <tqtabwidget.h>

#include <kgenericfactory.h>
#include <kurlrequester.h>
#include <tdemessagebox.h>
#include <tdeconfig.h>
#include <tdeapplication.h>
#include <kanimwidget.h>
#include <kpassivepopup.h>
#include <kiconloader.h>
#include <kstandarddirs.h>
#include <kactivelabel.h>

#include <kopeteaccountmanager.h>
#include <kopeteaccount.h>
#include <kopeteprotocol.h>

#include "otrprefs.h"
#include "otrpreferences.h"
#include "otrplugin.h"
#include "kopete_otr.h"

/**
  * @author Michael Zanetti
  */

typedef KGenericFactory<OTRPreferences> OTRPreferencesFactory;
K_EXPORT_COMPONENT_FACTORY( kcm_kopete_otr, OTRPreferencesFactory("kcm_kopete_otr"))

OTRPreferences::OTRPreferences(TQWidget *parent, const char* /*name*/, const TQStringList &args)
		: TDECModule(OTRPreferencesFactory::instance(), parent, args)
{
	( new TQVBoxLayout( this ) )->setAutoAdd( true );
	preferencesDialog = new OTRPrefsUI(this);

	
	this->addConfig( KopeteOtrKcfg::self(), preferencesDialog );
	KopeteOtrKcfg::self()->readConfig();
	load();



	otrlConfInterface = new OtrlConfInterface( preferencesDialog );

	connect( preferencesDialog->btGenFingerprint, TQ_SIGNAL(clicked()), TQ_SLOT(generateFingerprint()));
	connect( preferencesDialog->cbKeys, TQ_SIGNAL(activated(int)), TQ_SLOT(showPrivFingerprint(int)));
	connect( preferencesDialog->btVerify, TQ_SIGNAL(clicked()), TQ_SLOT(verifyFingerprint()));
	connect( preferencesDialog->twSettings, TQ_SIGNAL(currentChanged(TQWidget *)), TQ_SLOT(fillFingerprints()));
	connect( preferencesDialog->tbFingerprints, TQ_SIGNAL(currentChanged(int, int)), TQ_SLOT(updateButtons(int, int)));
	connect( preferencesDialog->btForget, TQ_SIGNAL( clicked() ), TQ_SLOT( forgetFingerprint() ) );

	int index = 0;
	int accountnr = 0;
	TQPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();
	if( !accounts.isEmpty() ){
		for ( TQPtrListIterator<Kopete::Account> it( accounts );
			Kopete::Account *account = it.current();
			++it ){
				if (  account->protocol()->pluginId() != "IRCProtocol" ){
					preferencesDialog->cbKeys->insertItem(account->accountId() + " (" + account->protocol()->displayName() + ")");
					privKeys.insert(index++, accountnr);
				}
				accountnr++;
		}
	}
	showPrivFingerprint( preferencesDialog->cbKeys->currentItem() );
	
	preferencesDialog->tbFingerprints->setColumnWidth( 0, 200 );
	preferencesDialog->tbFingerprints->setColumnWidth( 1, 80 );
	preferencesDialog->tbFingerprints->setColumnWidth( 2, 60 );
	preferencesDialog->tbFingerprints->setColumnWidth( 3, 400 );
	preferencesDialog->tbFingerprints->setColumnWidth( 4, 200 );

}

OTRPreferences::~OTRPreferences(){
}

void OTRPreferences::generateFingerprint()
{
	TQPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();

	if( (accounts.isEmpty())){
		return;
	}
	

	Kopete::Account *account = accounts.at( privKeys[preferencesDialog->cbKeys->currentItem()] );

	if ((otrlConfInterface->hasPrivFingerprint( account->accountId(), account->protocol()->displayName() ) ) && (KMessageBox::questionYesNo(this, i18n("Selected account already has a key. Do you want to create a new one?"), i18n("Overwrite key?")) !=3)) return;
	
	otrlConfInterface->generateNewPrivKey( account->accountId(), account->protocol()->displayName() );
	showPrivFingerprint( preferencesDialog->cbKeys->currentItem() );	
}

void OTRPreferences::showPrivFingerprint( int accountnr )
{
	TQPtrList<Kopete::Account> accounts = Kopete::AccountManager::self()->accounts();
	if( !accounts.isEmpty() ){
		Kopete::Account *account = accounts.at(privKeys[accountnr]);
		preferencesDialog->tlFingerprint->setText( otrlConfInterface->getPrivFingerprint( account->accountId(), account->protocol()->displayName() ) );
	}
}

void OTRPreferences::fillFingerprints(){
	TQTable *fingerprintsTable = preferencesDialog->tbFingerprints;
	preferencesDialog->tbFingerprints->setNumRows(0);
	TQValueList<TQStringList> list = otrlConfInterface->readAllFingerprints();
	TQValueList<TQStringList>::iterator it;
	int j = 0;
	for( it = list.begin(); it != list.end(); ++it ){
		preferencesDialog->tbFingerprints->setNumRows( preferencesDialog->tbFingerprints->numRows() +1 );
		fingerprintsTable->setItem(j, 0, new TQAlignTableItem(fingerprintsTable, TQTableItem::Never,
		                           OtrlChatInterface::self()->formatContact((*it)[0]), TQt::AlignLeft));
		for( int i = 1; i < 5; i++ ){
			//preferencesDialog->tbFingerprints->setText(j, i, (*it)[i] );
			fingerprintsTable->setItem(j,i, new TQAlignTableItem(fingerprintsTable, TQTableItem::Never,(*it)[i],TQt::AlignLeft));
 		}
		j++;
	}
	updateButtons( preferencesDialog->tbFingerprints->currentRow(), preferencesDialog->tbFingerprints->currentColumn() );
}

void OTRPreferences::verifyFingerprint(){

	int doVerify = KMessageBox::questionYesNo( 
		this, 
		i18n("Please contact %1 via another secure way and verify that the following Fingerprint is correct:").arg(preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 0 )) + "\n\n" + preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 3 ) + "\n\n" + i18n("Are you sure you want to trust this fingerprint?"), i18n("Verify fingerprint")  );
	

	if( doVerify == KMessageBox::Yes ){
		otrlConfInterface->verifyFingerprint( preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 3 ), true );
	} else {
		otrlConfInterface->verifyFingerprint( preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 3 ), false );
	}
	fillFingerprints();
}

void OTRPreferences::updateButtons( int row, int col ){
	if( row != -1 ){
		if( !otrlConfInterface->isEncrypted( preferencesDialog->tbFingerprints->text( row, 3 ) ) ){
			preferencesDialog->btForget->setEnabled( true );
		} else {
		preferencesDialog->btForget->setEnabled( false );
		}
		preferencesDialog->btVerify->setEnabled( true );
	} else {
		preferencesDialog->btVerify->setEnabled( false );
		preferencesDialog->btForget->setEnabled( false );
	}
}

void OTRPreferences::forgetFingerprint(){
	if( !otrlConfInterface->isEncrypted( preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 3 ) ) ){
		otrlConfInterface->forgetFingerprint( preferencesDialog->tbFingerprints->text( preferencesDialog->tbFingerprints->currentRow(), 3 ) );
		fillFingerprints();
	} else {
		updateButtons( preferencesDialog->tbFingerprints->currentRow(), preferencesDialog->tbFingerprints->currentColumn() );
	}
}

TQAlignTableItem :: TQAlignTableItem( TQTable *table, EditType editType, const TQString& text, int alignment )
	 : TQTableItem( table, editType, text ) {
	align = alignment;
}


#include "otrpreferences.moc"
