/***************************************************************************
*   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 <tqtooltip.h>
#include <tqpopupmenu.h>

#include <tdelocale.h>
#include <kdebug.h>
#include <kurl.h>
#include <tdeapplication.h>
#include <kprocio.h>
#include <tdemessagebox.h>

#include <cstdlib>

#include "torkconfig.h"
#include "tork.h"
#include "hidsrvwizard.h"


void MyHidden::init()
{

    TQStringList hiddenServices = TorkConfig::hiddenServices();
	for ( TQStringList::Iterator it = hiddenServices.begin(); it != hiddenServices.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;

        new TQListViewItem(servicesList,(*it).section("\n",-6,-6),(*it).section("\n",-5,-5),
            (*it).section("\n",-4,-4),(*it).section("\n",-3,-3),(*it).section("\n",-2,-2),(*it).section("\n",-1));
    }

    deleteService->setEnabled(false);
    startService->setEnabled(false);
    testService->setEnabled(false);
    publishService->setEnabled(false);
}

void MyHidden::destroyed()
{

}

void MyHidden::createService_clicked()
{

    if (static_cast<tork*>(this->topLevelWidget()->parentWidget())->connectedToTor()){
        HidSrvWizard wizard;
        wizard.setCaption( i18n( "Hidden Services Wizard" ));
        connect( &wizard, TQ_SIGNAL(createService(const TQString&,const TQString&)),this->topLevelWidget()->parent(), TQ_SLOT(createService(const TQString&,const TQString& )) );
        connect( &wizard, TQ_SIGNAL(addService(const TQString&,const TQString&,const TQString&,const TQString&,const TQString&,const TQString&)), TQ_SLOT(addService(const TQString&,const TQString&,const TQString&,const TQString&,const TQString&,const TQString&)) );
        wizard.exec();
    }else{
        TQString caption = i18n("Not Connected To Tor!");
        TQString message = i18n("<p>TorK needs to be connected to Tor in order to create a hidden service. <br>"
                            "<b>To create a hidden service, first start TorK!");
        KMessageBox::information (this, message, caption);
    }


}

void MyHidden::updateServices()
{
    if ( servicesList->childCount() > 0 ) {
        TQStringList v_hiddenServices;
        TQListViewItemIterator it( servicesList );
        while ( it.current() ) {
            TQString s_hiddenServices = it.current()->text(0) + "\n" + it.current()->text(1)
                                        + "\n" + it.current()->text(2) + "\n" + it.current()->text(3)
                                        + "\n" + it.current()->text(4)+ "\n" + it.current()->text(5);
            v_hiddenServices.append(s_hiddenServices);
	        ++it;
        }
        TorkConfig::setHiddenServices( v_hiddenServices );
    }else
        TorkConfig::setHiddenServices( "" );
    TorkConfig::writeConfig();
}

void MyHidden::addService(const TQString& nick,const TQString& publicport,const TQString& actualaddress,const TQString& toraddress,const TQString& folder,const TQString& servicefolder)
{
    new TQListViewItem(servicesList,toraddress,nick,publicport,actualaddress,folder,servicefolder);
    updateServices();
}

void MyHidden::deleteService_clicked()
{
    TQString serviceDetails = servicesList->currentItem()->text(5);
    TQString serviceAddress = servicesList->currentItem()->text(0);

    delete servicesList->currentItem();
    TQString caption = i18n("Service deleted!");
    TQString message = i18n("<p>The hidden service %1 has been de-configured. <br>"
                        "<b>However you will need to delete the service details in %2 yourself! Please do this!").arg(serviceAddress).arg(serviceDetails);
    KMessageBox::information (this, message, caption);

    updateServices();
}


void MyHidden::startService_clicked()
{

    KProcIO* thttpdproc = new KProcIO();
    thttpdproc->setUseShell(true);

	TQString curpath = (TQString) getenv("PATH");
	thttpdproc->setEnvironment("PATH",curpath + ":/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin");

    *thttpdproc << "thttpd  -p " << servicesList->currentItem()->text(3).section(":",1) 
                << "-h " << servicesList->currentItem()->text(3).section(":",0,0)
                << "-d " << servicesList->currentItem()->text(4);

 	connect( thttpdproc, TQ_SIGNAL(processExited(TDEProcess *)),
 			TQ_SLOT(thttpdprocExited(TDEProcess *)) );

	thttpdproc->start(KProcIO::NotifyOnExit)    ;

}

void MyHidden::thttpdprocExited(TDEProcess *proc)
{
    TQString caption;
    TQString message;

    if (proc->exitStatus() == 0){
        caption = i18n("Hidden Web Service Started");
        message = i18n("<p>Simple web service started. Test the service to ensure it's running. <br>"
                            "<b>thttpd  -p %1 -h %2 -d %3").arg(servicesList->currentItem()->text(3).section(":",1)) 
                            .arg(servicesList->currentItem()->text(3).section(":",0,0))
                            .arg(servicesList->currentItem()->text(4));
    }else{
        caption = i18n("Hidden Web Service Failed");
        message = i18n("<p>Couldn't start the simple web service. Thttpd may not be installed properly. <br>"
                            "<b>thttpd  -p %1 -h %2 -d %3").arg(servicesList->currentItem()->text(3).section(":",1)) 
                            .arg(servicesList->currentItem()->text(3).section(":",0,0))
                            .arg(servicesList->currentItem()->text(4));

    }

    KMessageBox::information (this, message, caption);

}
void MyHidden::servicesList_selectionChanged()
{
    if (servicesList->currentItem()->text(4).isEmpty())
        startService->setEnabled(false);
    else
        startService->setEnabled(true);
    deleteService->setEnabled(true);
    testService->setEnabled(true);
    publishService->setEnabled(true);
}


void MyHidden::startAllServices_clicked()
{

}


void MyHidden::testService_clicked()
{
    if ((TorkConfig::tDEUsesTor()) &&
        (static_cast<tork*>(this->topLevelWidget()->parentWidget())->connectedToTor())){
        KURL url = TQString("http://%1").arg(servicesList->currentItem()->text(0));
        kapp->invokeBrowser(url.url(), "0");
    }else{
        TQString caption = i18n("Not Connected To Tor!");
        TQString message = i18n("<p>Konqueror and TorK need to be using Tor in order to test a hidden service. <br>"
                            "<b>To test a hidden service, first start TorK and enable Konqueror to use Tor!");
        KMessageBox::information (this, message, caption);
    }

}


void MyHidden::publishService_clicked()
{
    if ((TorkConfig::tDEUsesTor()) &&
        (static_cast<tork*>(this->topLevelWidget()->parentWidget())->connectedToTor())){

       KURL url = TQString("tor:6sxoyfb3h2nvok2d.onion/tor/FrontPage?action=edit");
       kapp->invokeBrowser(url.url(), "0");
    }else{
        TQString caption = i18n("Not Connected To Tor!");
        TQString message = i18n("<p>Konqueror and TorK need to be using Tor in order to publish a hidden service. <br>"
                            "<b>To publish a hidden service, first start TorK and enable Konqueror to use Tor!");
        KMessageBox::information (this, message, caption);
    }


}
