/***************************************************************************
 * $Id: torservers.ui.h,v 1.22 2009/01/17 15:49:08 hoganrobert Exp $
 *   Copyright (C) 2006 - 2008 Robert Hogan                                *
 *   robert@roberthogan.net                                                *
 *                                                                         *
 *   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 St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************/
#include "torkconfig.h"
#include "crypto.h"
#include <klocale.h>
#include <qtooltip.h>
#include <qpopupmenu.h>
#include <kdebug.h>
#include <kiconloader.h>

#ifndef EXTERNAL_GEOIP
# include "GeoIP-1.4.0/libGeoIP/GeoIP.h"
#else
# include <GeoIP.h>
#endif

typedef QMap<QString, QString> codemap;
QString ccode;
QString cname;
codemap ccodes;
QStringList blockCCs;

void TorServers::init()
{
    
    ExcludeNodes->setSelectionMode( QListView::Extended );
    ExcludeNodes->setColumnWidthMode(0, QListView::Manual);
    ExcludeNodes->hideColumn(0);
    ExcludeNodes->header()->setResizeEnabled(FALSE, 0);
    ExcludeNodes->setColumnWidthMode(1, QListView::Manual);
    ExcludeNodes->hideColumn(1);
    ExcludeNodes->header()->setResizeEnabled(FALSE, 1);
    ExcludeNodes->setColumnWidthMode(2, QListView::Manual);
    ExcludeNodes->hideColumn(2);
    ExcludeNodes->header()->setResizeEnabled(FALSE, 2);
    ExcludeNodes->setResizeMode( QListView::LastColumn );

    ExitNodes->setSelectionMode( QListView::Extended );
    ExitNodes->setColumnWidthMode(0, QListView::Manual);
    ExitNodes->hideColumn(0);
    ExitNodes->header()->setResizeEnabled(FALSE, 0);
    ExitNodes->setColumnWidthMode(1, QListView::Manual);
    ExitNodes->hideColumn(1);
    ExitNodes->header()->setResizeEnabled(FALSE, 1);
    ExitNodes->setColumnWidthMode(2, QListView::Manual);
    ExitNodes->hideColumn(2);
    ExitNodes->header()->setResizeEnabled(FALSE, 2);
    ExitNodes->setResizeMode( QListView::LastColumn );
    QListViewItem *tm;
    QString fp;
    QString nick;
    QString geoipcc;
    QString countryName;

    QStringList excludeCountries = TorkConfig::excludeCountries();
    for ( QStringList::Iterator it = excludeCountries.begin(); it != excludeCountries.end(); ++it )
	{
        countryName = GeoIP_country_name[(*it).toInt()];
        ccodes[countryName] = (*it);
        CountryList->insertItem(countryName);
    }

//     QStringList preferredCountries = TorkConfig::preferredCountries();
//     for ( QStringList::Iterator it = preferredCountries.begin(); it != preferredCountries.end(); ++it )
// 	{
//         countryName = GeoIP_country_name[(*it).toInt()];
//         ccodes[countryName] = (*it);
//         PreferredCountryList->insertItem(countryName);
//     }

    QStringList existingServers = TorkConfig::excludeServersHistory();

	for ( QStringList::Iterator it = existingServers.begin(); it != existingServers.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;

        fp.setLength(0);
        nick.setLength(0);
        geoipcc = (*it).section("-",0,0);
        fp = (*it).section("-",1,1);
        nick = (*it).section("-",2);
        countryName = GeoIP_country_name[(geoipcc).toInt()];

        tm = new QListViewItem(ExcludeNodes,countryName,geoipcc,fp,nick);
        tm->setPixmap(3,QPixmap(SmallIcon("tork_" + QString(GeoIP_country_code[geoipcc.toInt()]).lower())));


    }

    existingServers = TorkConfig::includeServersHistory();

	for ( QStringList::Iterator it = existingServers.begin(); it != existingServers.end(); ++it )
	{

		if ((*it).isEmpty())
			continue;

        fp.setLength(0);
        nick.setLength(0);
        geoipcc = (*it).section("-",0,0);
        fp = (*it).section("-",1,1);
        nick = (*it).section("-",2);
        countryName = GeoIP_country_name[(geoipcc).toInt()];

        tm = new QListViewItem(ExitNodes,countryName,geoipcc,fp,nick);
        tm->setPixmap(3,QPixmap(SmallIcon("tork_" + QString(GeoIP_country_code[geoipcc.toInt()]).lower())));

//         CandidateList->insertItem( nick );

	}
    QStringList mapAddresses = TorkConfig::mapAddress();

	for ( QStringList::Iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;
        QString entry = (*it).section(" ",1,1);
        QString destination = entry.section(".",0,-3);
        QString server = entry.section(".",-2,-2);
        QString waypoint = entry.section(".",-1,-1);

        tm = new QListViewItem(MapAddress,destination,server,waypoint);
    }

    QListViewItemIterator it(AllowUnverifiedNodes);
    while ( it.current() ) {
        if (TorkConfig::allowUnverifiedNodes().contains(it.current()->text(0)))
            AllowUnverifiedNodes->setSelected(*it,true);
        ++it;
    }

    CountryList->sort(true);
//     PreferredCountryList->sort(true);

    kcfg_StrictExitNodes->setEnabled((ExitNodes->childCount() == 0)?false:true);

}

void TorServers::destroy()
{
//     QStringList cclist;
//     for (unsigned int index = 0; index != CountryList->count(); ++index){
//         cclist.append(ccodes[CountryList->item(index)->text()]);
//     }
//     TorkConfig::setExcludeCountries(cclist);
// 
//     cclist.clear();
//     for (unsigned int index = 0; index != PreferredCountryList->count(); ++index){
//         cclist.append(ccodes[PreferredCountryList->item(index)->text()]);
//     }
//     TorkConfig::setPreferredCountries(cclist);
// 
//     TorkConfig::writeConfig();

}

QString TorServers::ccode(const QString &country)
{
    return ccodes[country];
}

void TorServers::pushButton6_clicked()
{

    new QListViewItem(MapAddress,Destination->text(), CandidateList->currentText(), WayPoints->currentText());
}



void TorServers::MapAddress_contextMenuRequested( QListViewItem *, const QPoint &point, int )
{

    QPopupMenu *menu = new QPopupMenu( MapAddress );

    menu->clear();
    menu->insertItem( "Delete Entry", this,SLOT(slotDeleteEntry()) );
    menu->popup( point );

}


void TorServers::slotDeleteEntry( )
{

    QListViewItemIterator it(MapAddress, QListViewItemIterator::Selected);
    while ( it.current() ) {
        if (MapAddress->isSelected( it.current()))
            delete it.current();
        ++it;
    }


}


void TorServers::MapAddress_returnPressed( QListViewItem * )
{

}


void TorServers::clearSelectedCountries_clicked()
{

    QValueList<QListViewItem*> itemsToDelete;

    QListViewItemIterator it(ExcludeNodes, QListViewItemIterator::Selected);
    while ( it.current() ) {
        if (CountryList->findItem(it.current()->text(0))->isSelected()){
            itemsToDelete << it.current();
        }
        ++it;
    }

    for ( QValueList<QListViewItem*>::Iterator itt = itemsToDelete.begin(); itt != itemsToDelete.end(); ++itt ){
        delete (*itt);
    }

    QValueList<QListBoxItem*> countriesToDelete;

    for (unsigned int index = 0; index != CountryList->count(); ++index){
        if (CountryList->item(index)->isSelected() )
            countriesToDelete << CountryList->item(index);
    }

    for ( QValueList<QListBoxItem*>::Iterator itb = countriesToDelete.begin(); 
        itb != countriesToDelete.end(); ++itb ){
        delete (*itb);
    }

    CountryList->clearSelection();
}


void TorServers::clearSelectedNodes_clicked()
{

    QValueList<QListViewItem*> itemsToDelete;

    QListViewItemIterator it(ExcludeNodes, QListViewItemIterator::Selected);
    while ( it.current() ) {
        itemsToDelete << it.current();
        ++it;
    }

    for ( QValueList<QListViewItem*>::Iterator itt = itemsToDelete.begin(); itt != itemsToDelete.end(); ++itt ){
        delete (*itt);
    }

    CountryList->clearSelection();
}


// void TorServers::clearSelectedPreferredCountries_clicked()
// {
// 
//     QValueList<QListViewItem*> itemsToDelete;
// 
//     QListViewItemIterator it(ExitNodes, QListViewItemIterator::Selected);
//     while ( it.current() ) {
//         if (PreferredCountryList->findItem(it.current()->text(0))->isSelected()){
//             itemsToDelete << it.current();
//         }
//         ++it;
//     }
// 
//     for ( QValueList<QListViewItem*>::Iterator itt = itemsToDelete.begin(); itt != itemsToDelete.end(); ++itt ){
//         delete (*itt);
//     }
// 
//     QValueList<QListBoxItem*> countriesToDelete;
// 
//     for (unsigned int index = 0; index != PreferredCountryList->count(); ++index){
//         if (PreferredCountryList->item(index)->isSelected() )
//             countriesToDelete << PreferredCountryList->item(index);
//     }
// 
//     for ( QValueList<QListBoxItem*>::Iterator itb = countriesToDelete.begin(); 
//         itb != countriesToDelete.end(); ++itb ){
//         delete (*itb);
//     }
// 
//     PreferredCountryList->clearSelection();
// }


void TorServers::clearSelectedPreferredNodes_clicked()
{

    QValueList<QListViewItem*> itemsToDelete;

    QListViewItemIterator it(ExitNodes, QListViewItemIterator::Selected);
    while ( it.current() ) {
        itemsToDelete << it.current();
        ++it;
    }

    for ( QValueList<QListViewItem*>::Iterator itt = itemsToDelete.begin(); itt != itemsToDelete.end(); ++itt ){
        delete (*itt);
    }

    if (ExitNodes->childCount() == 0){
      kcfg_StrictExitNodes->setEnabled(false);
      kcfg_StrictExitNodes->setChecked(false);
    }
}



void TorServers::pushButton6_2_clicked()
{

    QListViewItemIterator it(AllowUnverifiedNodes, QListViewItemIterator::Selected);
    while ( it.current() ) {
        it.current()->listView()->setSelected(it.current(),false);
        ++it;
    }

}

void TorServers::CountryList_clicked( )
{

    QStringList selectedCountries;
    for ( unsigned int i = 0; i < CountryList->count(); ++i){
        if (CountryList->isSelected(i)){
            selectedCountries.append(CountryList->item(i)->text());
        }
    }

    kdDebug() << "country list clicked" << endl;
    QListViewItemIterator it( ExcludeNodes );
    while ( it.current() ) {
        QListViewItem *item = it.current();
        if (selectedCountries.contains(item->text(0)))
            item->setSelected(true);
        else
            item->setSelected(false);
        it++;
    }
    ExcludeNodes->repaintContents();

}

// void TorServers::PreferredCountryList_clicked( QListBoxItem * curitem)
// {
// 
//     QListViewItemIterator it( ExitNodes );
//     while ( it.current() ) {
//         QListViewItem *item = it.current();
//         if (curitem){
//             if (item->text(0) == curitem->text())
//                 item->setSelected(curitem->isSelected());
//         }
//         it++;
//     }
//     ExitNodes->repaintContents();
// 
// }



// <connections>
//     <connection>
//         <sender>pushButton6</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>pushButton6_clicked()</slot>
//     </connection>
//     <connection>
//         <sender>MapAddress</sender>
//         <signal>contextMenuRequested(QListViewItem*,const QPoint&amp;,int)</signal>
//         <receiver>TorServers</receiver>
//         <slot>MapAddress_contextMenuRequested(QListViewItem*,const QPoint&amp;,int)</slot>
//     </connection>
//     <connection>
//         <sender>MapAddress</sender>
//         <signal>returnPressed(QListViewItem*)</signal>
//         <receiver>TorServers</receiver>
//         <slot>MapAddress_returnPressed(QListViewItem*)</slot>
//     </connection>
//     <connection>
//         <sender>clearSelected</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>clearSelected_clicked()</slot>
//     </connection>
//     <connection>
//         <sender>clearSelected_2</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>clearSelected_2_clicked()</slot>
//     </connection>
//     <connection>
//         <sender>clearSelected_3</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>clearSelected_3_clicked()</slot>
//     </connection>
//     <connection>
//         <sender>clearSelected_3_2</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>clearSelected_3_2_clicked()</slot>
//     </connection>
//     <connection>
//         <sender>pushButton6_2</sender>
//         <signal>clicked()</signal>
//         <receiver>TorServers</receiver>
//         <slot>pushButton6_2_clicked()</slot>
//     </connection>
// </connections>
// <includes>
//     <include location="local" impldecl="in implementation">torservers.ui.h</include>
// </includes>
// <slots>
//     <slot>pushButton6_clicked()</slot>
//     <slot>MapAddress_contextMenuRequested( QListViewItem *, const QPoint &amp; point, int )</slot>
//     <slot>slotDeleteEntry()</slot>
//     <slot>MapAddress_returnPressed( QListViewItem * )</slot>
//     <slot>clearSelected_clicked()</slot>
//     <slot>clearSelected_2_clicked()</slot>
//     <slot>clearSelected_3_clicked()</slot>
//     <slot>clearSelected_3_2_clicked()</slot>
//     <slot>pushButton6_2_clicked()</slot>
// </slots>
// <functions>
//     <function access="private" specifier="non virtual">init()</function>
// </functions>
// <layoutdefaults spacing="6" margin="11"/>
// </UI>
