/***************************************************************************
                          dctranslator.cpp  -  description
                             -------------------
    begin                : Die Nov 19 2002
    copyright            : (C) 2002 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

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

#include <qapplication.h>
#include <qhttp.h>
#include <qnetwork.h>
#include <qurloperator.h>
#include <qregexp.h>
#include <qurl.h>
#include <qinputdialog.h>

#include <dcgui.h>
#include <dcevent.h>

#include "dctranslator.h"

DCTranslator * g_pTranslator = 0;

DCTranslator::DCTranslator(QWidget * /*parent*/, const char * /*name*/ ) // : QWidget(parent,name) {
{
#if QT_VERSION > 0x030000
	qInitNetworkProtocols();
#endif
	pOp = new QUrlOperator();

	InitDocument();
	
	g_pTranslator = this;
}

DCTranslator::~DCTranslator()
{
	g_pTranslator = NULL;
	
	if ( pOp )
	{
		delete pOp;
	}
}

/** */
void DCTranslator::InitDocument()
{
	m_sLanguage = "en_de";

	connect( pOp, SIGNAL(data(const QByteArray &, QNetworkOperation *)), this, SLOT(slotData(const QByteArray &, QNetworkOperation *)) );
	connect( pOp, SIGNAL(dataTransferProgress(int, int, QNetworkOperation*)), this, SLOT(slotDataTransferProgress( int, int, QNetworkOperation *)) );
	connect( pOp, SIGNAL(finished( QNetworkOperation *)), this, SLOT(slotFinished( QNetworkOperation *)) );
}

/** */
QString DCTranslator::SelectLanguage( CString lang )
{
	int index;
	bool ok = FALSE;
	QStringList lst;
	QString res;

	lst << "zh_en" << "zt_en" << "en_zh" << "en_zt" << "en_nl" << "en_fr" << "en_de" <<
	       "en_el" << "en_it" << "en_ja" << "en_ko" << "en_pt" << "en_ru" << "en_es" <<
	       "nl_en" << "nl_fr" << "fr_en" << "fr_de" << "fr_el" << "fr_it" << "fr_pt" <<
	       "fr_nl" << "fr_es" << "de_en" << "de_fr" << "el_en" << "el_fr" << "it_en" <<
	       "it_fr" << "ja_en" << "ko_en" << "pt_en" << "pt_fr" << "ru_en" << "es_en" <<
	       "es_fr";



	index = lst.findIndex(lang.Data());

	if ( index ==  -1 )
	{
		index = 0;
	}

	res = QInputDialog::getItem( tr("Translator"), tr("Choose a language"), lst, index, FALSE, &ok, 0 );

	if ( ok )
	{
		return res;
	}
	else
	{
		return m_sLanguage;
	}
}

/** */
bool DCTranslator::Translate( QObject * sender, QString lang, QString text )
{
	DC_TranslationEvent * TranslationEvent=0;
	QString url,tr_text;

	// convert text to correct html ... 
	tr_text = text;

	QUrl::encode(tr_text);

	url  = "http://babelfish.altavista.com/babelfish/tr?doit=done&tt=urltext&intl=1";
	url += "&urltext=" + tr_text;
	url += "&lp=";

	if ( lang == "" )
		url += m_sLanguage;
	else
		url += lang;

	if ( m_UrlList.Get( url.ascii(), (CObject *&)TranslationEvent ) == 0 )
	{
		return FALSE;
	}

	TranslationEvent = new 	DC_TranslationEvent(EVENT_TRANSLATION);

	TranslationEvent->m_bTranslate   = FALSE;
	TranslationEvent->m_pReceiver    = sender;
	TranslationEvent->m_sOriginal    = text;
	TranslationEvent->m_sTranslation = "";

	m_UrlList.Add( url.ascii(), (CObject*)TranslationEvent );

	pOp->get(url);

	return TRUE;
}

/** */
void DCTranslator::slotData( const QByteArray & data, QNetworkOperation * no )
{
	DC_TranslationEvent * TranslationEvent=0;

	if ( m_UrlList.Get( no->arg(0).ascii(), (CObject *&)TranslationEvent ) != 0 )
	{
		printf("URL NOT FOUND: %s\n",no->arg(0).ascii());
		return;
	}

	TranslationEvent->m_sTranslation += QString().setLatin1(data.data(),data.size());
}

/** */
void DCTranslator::slotDataTransferProgress( int bytesDone, int bytesTotal, QNetworkOperation * )
{
	printf("%d/%d\n",bytesDone,bytesTotal);
//	QString s;
//	s.sprintf("%d/%d",bytesDone,bytesTotal);
//	TextLabel_Status->setText(s);
}

/** */
void DCTranslator::slotFinished( QNetworkOperation * op )
{
	DC_TranslationEvent * TranslationEvent=0;

	if ( m_UrlList.Get( op->arg(0).ascii(), (CObject *&)TranslationEvent ) != 0 )
	{
		printf("URL NOT FOUND: %s\n",op->arg(0).ascii());
		return;
	}

	printf("STATE: %d\n",op->state());

	switch( op->state() )
	{
		case QNetworkProtocol::StWaiting:
			return;
			break;
		case QNetworkProtocol::StInProgress:
			return;
			break;
		case QNetworkProtocol::StDone:
		{
			QString s,s1;
			int i1,i2;
			s1 = "<div style=padding:10px;";
			s = TranslationEvent->m_sTranslation;
//			printf("%s\n",s.ascii());fflush(stdout);
			if ( (i1 = s.find(s1)) == -1 )
				TranslationEvent->m_sTranslation = "";
			else
			{
				// find tag end
				if ( (i1 = s.find(">",i1)) == -1 )
					TranslationEvent->m_sTranslation = "";
 				else if ( (i2 = s.find("</div>",i1)) == -1 )
					TranslationEvent->m_sTranslation = "";
				else
				{
//					printf("POSITION: %d %d\n",i1,i2);fflush(stdout);
					TranslationEvent->m_sTranslation = s.mid(i1+1,i2-i1-1);
//					printf("translate: '%s'\n",TranslationEvent->m_sTranslation.ascii());
					// remove 0x0a at end
					while( (TranslationEvent->m_sTranslation.length() > 0) && (TranslationEvent->m_sTranslation.ascii()[TranslationEvent->m_sTranslation.length()-1] == 0x0a) )
						TranslationEvent->m_sTranslation = TranslationEvent->m_sTranslation.left(TranslationEvent->m_sTranslation.length()-1);
					TranslationEvent->m_bTranslate = TRUE;
				}
				printf("translate: '%s'\n",TranslationEvent->m_sTranslation.ascii());
			}

			break;
		}

//		case QNetworkProtocol::StFailed:
//		case QNetworkProtocol::StStopped:
		default:
			TranslationEvent->m_sTranslation = "";
			TranslationEvent->m_bTranslate = FALSE;
			break;
	}

	m_UrlList.Remove(op->arg(0).ascii());

	QApplication::postEvent( TranslationEvent->m_pReceiver, TranslationEvent );
}
