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

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <tqtooltip.h>
#include <tqpopupmenu.h>

#include <tdelocale.h>
#include <kdebug.h>
#include <kiconloader.h>

#include "torkconfig.h"
#include "crypto.h"

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

typedef TQMap<TQString, TQString> codemap;
TQString ccode;
TQString cname;
codemap ccodes;
TQStringList blockCCs;

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

    ExitNodes->setSelectionMode( TQListView::Extended );
    ExitNodes->setColumnWidthMode(0, TQListView::Manual);
    ExitNodes->hideColumn(0);
    ExitNodes->header()->setResizeEnabled(false, 0);
    ExitNodes->setColumnWidthMode(1, TQListView::Manual);
    ExitNodes->hideColumn(1);
    ExitNodes->header()->setResizeEnabled(false, 1);
    ExitNodes->setColumnWidthMode(2, TQListView::Manual);
    ExitNodes->hideColumn(2);
    ExitNodes->header()->setResizeEnabled(false, 2);
    ExitNodes->setResizeMode( TQListView::LastColumn );
    TQListViewItem *tm;
    TQString fp;
    TQString nick;
    TQString geoipcc;
    TQString countryName;

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

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

    TQStringList existingServers = TorkConfig::excludeServersHistory();

	for ( TQStringList::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 TQListViewItem(ExcludeNodes,countryName,geoipcc,fp,nick);
        tm->setPixmap(3,TQPixmap(SmallIcon("tork_" + TQString(GeoIP_country_code[geoipcc.toInt()]).lower())));


    }

    existingServers = TorkConfig::includeServersHistory();

	for ( TQStringList::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 TQListViewItem(ExitNodes,countryName,geoipcc,fp,nick);
        tm->setPixmap(3,TQPixmap(SmallIcon("tork_" + TQString(GeoIP_country_code[geoipcc.toInt()]).lower())));

//         CandidateList->insertItem( nick );

	}
    TQStringList mapAddresses = TorkConfig::mapAddress();

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

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

    TQListViewItemIterator 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()
{
//     TQStringList 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();

}

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

void TorServers::pushButton6_clicked()
{

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



void TorServers::MapAddress_contextMenuRequested( TQListViewItem *, const TQPoint &point, int )
{

    TQPopupMenu *menu = new TQPopupMenu( MapAddress );

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

}


void TorServers::slotDeleteEntry( )
{

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


}


void TorServers::MapAddress_returnPressed( TQListViewItem * )
{

}


void TorServers::clearSelectedCountries_clicked()
{

    TQValueList<TQListViewItem*> itemsToDelete;

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

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

    TQValueList<TQListBoxItem*> countriesToDelete;

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

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

    CountryList->clearSelection();
}


void TorServers::clearSelectedNodes_clicked()
{

    TQValueList<TQListViewItem*> itemsToDelete;

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

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

    CountryList->clearSelection();
}


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


void TorServers::clearSelectedPreferredNodes_clicked()
{

    TQValueList<TQListViewItem*> itemsToDelete;

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

    for ( TQValueList<TQListViewItem*>::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()
{

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

}

void TorServers::CountryList_clicked( )
{

    TQStringList 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;
    TQListViewItemIterator it( ExcludeNodes );
    while ( it.current() ) {
        TQListViewItem *item = it.current();
        if (selectedCountries.contains(item->text(0)))
            item->setSelected(true);
        else
            item->setSelected(false);
        it++;
    }
    ExcludeNodes->repaintContents();

}

// void TorServers::PreferredCountryList_clicked( TQListBoxItem * curitem)
// {
// 
//     TQListViewItemIterator it( ExitNodes );
//     while ( it.current() ) {
//         TQListViewItem *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(TQListViewItem*,const TQPoint&amp;,int)</signal>
//         <receiver>TorServers</receiver>
//         <slot>MapAddress_contextMenuRequested(TQListViewItem*,const TQPoint&amp;,int)</slot>
//     </connection>
//     <connection>
//         <sender>MapAddress</sender>
//         <signal>returnPressed(TQListViewItem*)</signal>
//         <receiver>TorServers</receiver>
//         <slot>MapAddress_returnPressed(TQListViewItem*)</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( TQListViewItem *, const TQPoint &amp; point, int )</slot>
//     <slot>slotDeleteEntry()</slot>
//     <slot>MapAddress_returnPressed( TQListViewItem * )</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>
