/***************************************************************************
*   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 <tdelocale.h>
#include <ntqtooltip.h>
#include <ntqpopupmenu.h>
#include <kdebug.h>
#include <tdehtml_part.h>
#include <dom/html_misc.h>
#include <tdemessagebox.h>

TDEHTMLPart *filelist;

void FirewallsProxies::init()
{

    filelist = new TDEHTMLPart();

    TQStringList existingMaps = TorkConfig::reachableAddresses();
    TQListViewItem *tm;
	for ( TQStringList::Iterator it = existingMaps.begin(); it != existingMaps.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;
        TQString entry = (*it).section(":",0,0);
        TQString port = (*it).section(":",1,1);

        tm = new TQListViewItem(ReachableAddresses,port);
    }

    existingMaps = TorkConfig::bridge();
	for ( TQStringList::Iterator it = existingMaps.begin(); it != existingMaps.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;
        TQString entry = (*it).section(":",0,0);
        TQString port = (*it).section(" ",0,0).section(":",1,1);
        TQString key = (*it).section(" ",1);

        tm = new TQListViewItem(Bridge,entry,port,key);
    }

    if (TorkConfig::currentTorVersion().left(3) == "0.1"){
        tabWidget->removePage(tabWidget->page(0));
    }

}
void FirewallsProxies::pushAdd_clicked()
{
    new TQListViewItem(ReachableAddresses,Port->text());

}



void FirewallsProxies::ReachableAddresses_contextMenuRequested( TQListViewItem *, const TQPoint &point, int )
{

    TQPopupMenu *menu = new TQPopupMenu( ReachableAddresses );

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

}

void FirewallsProxies::slotDeleteEntry( )
{

    TQValueList<TQListViewItem*> itemsToDelete;
    TQListViewItemIterator it(ReachableAddresses, TQListViewItemIterator::Selected);
    while ( it.current() ) {
            itemsToDelete << it.current();
        ++it;
    }

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

}

void FirewallsProxies::kcfg_FascistFirewall_toggled( bool on )
{
    Firewall->setEnabled(on);
}

void FirewallsProxies::kcfg_UseProxy_toggled( bool on)
{
    Proxies->setEnabled(on);
}

void FirewallsProxies::kcfg_HttpProxyHost_textChanged( const TQString & text)
{
    kcfg_HttpsProxyHost->setText(text);
}


void FirewallsProxies::kcfg_HttpProxyPort_valueChanged( int text)
{
    kcfg_HttpsProxyPort->setValue(text);
}


void FirewallsProxies::kcfg_HttpProxyAuthenticatorUserName_textChanged( const TQString & text)
{
    kcfg_HttpsProxyAuthenticatorUserName->setText(text);
}


void FirewallsProxies::kcfg_HttpProxyAuthenticatorPassword_textChanged( const TQString & text)
{
    kcfg_HttpsProxyAuthenticatorPassword->setText(text);
}




void FirewallsProxies::pushBridgeAdd_clicked()
{
    new TQListViewItem(Bridge,BridgeAddress->text(),BridgePort->text(),BridgeKey->text());

}


void FirewallsProxies::kcfg_UseBridges_toggled( bool on)
{
    BridgePanel->setEnabled(on);
    emit uncensorSelected(on);
}


void FirewallsProxies::Bridge_contextMenuRequested( TQListViewItem *, const TQPoint & point, int )
{
    TQPopupMenu *menu = new TQPopupMenu( Bridge );

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

}

void FirewallsProxies::slotDeleteBridgesEntry( )
{

    TQValueList<TQListViewItem*> itemsToDelete;
    TQListViewItemIterator it(Bridge, TQListViewItemIterator::Selected);
    while ( it.current() ) {
            itemsToDelete << it.current();
        ++it;
    }

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

}


void FirewallsProxies::slotGetBridges( )
{

    connect( filelist, SIGNAL( completed() ), this,
		SLOT( parseBridges() ) );

    filelist->openURL("https://bridges.torproject.org");
}

void FirewallsProxies::parseBridges()
{

    disconnect( filelist, SIGNAL( completed() ), this,
	SLOT( parseBridges() ) );

    const DOM::HTMLCollection links = filelist->htmlDocument().all();
    if (links.length() == 0){
           KMessageBox::information (this,i18n( "Could not contact update server!" ));
           return;
    }
    

    for (unsigned int j=0; j != links.length(); j++ ){
       const DOM::Node linkNode = links.item( j );
       if ( linkNode.isNull() || linkNode.nodeType() != DOM::Node::ELEMENT_NODE )
            continue;

       DOM::HTMLElement elem = static_cast<DOM::HTMLElement>( linkNode );
       if (elem.getAttribute("id") == "bridges"){
          TQStringList bridges = TQStringList::split("bridge ",elem.innerText().string());

          for ( TQStringList::Iterator it = bridges.begin(); it != bridges.end(); ++it )
          {
              if ((*it).isEmpty())
                  continue;
              TQString entry = (*it).section(":",0,0);
              TQString port = (*it).section(" ",0,0).section(":",1,1);
              TQString key = (*it).section(" ",1);
              if (((TQListViewItem*) Bridge->findItem(key,2)) == 0)
                  new TQListViewItem(Bridge,entry,port,key);
              else
                  KMessageBox::information (this,i18n( "Already have server :%1" ).arg((*it)));
          }


       }
    }
}


