/*  *************************************************************************
    *   copyright: (C) 2003 Richard Lärkäng <nouseforaname@home.se>         *
    *   copyright: (C) 2003 Gav Wood <gav@kde.org>                          *
    *************************************************************************
*/

/*  *************************************************************************
    *                                                                       *
    * 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 <tqcombobox.h>
#include <tqlayout.h>

#include <tdelocale.h>
#include <kurlrequester.h>
#include <tdemessagebox.h>
#include <kprocess.h>
#include <kdebug.h>
#include <tdeconfigbase.h>

#include "kopeteaccount.h"
#include "kopeteuiglobal.h"

#include "smsclient.h"
#include "smsclientprefs.h"
#include "smsprotocol.h"

SMSClient::SMSClient(Kopete::Account* account)
	: SMSService(account)
{
	prefWidget = 0L;
}

SMSClient::~SMSClient()
{
}

void SMSClient::setWidgetContainer(TQWidget* parent, TQGridLayout* layout)
{
	kdWarning( 14160 ) << k_funcinfo << "ml: " << layout << ", " << "mp: " << parent << endl;
	m_parent = parent;
	m_layout = layout;
	TQWidget *configWidget = configureWidget(parent);
	layout->addMultiCellWidget(configWidget, 0, 1, 0, 1);
	configWidget->show();
}

void SMSClient::send(const Kopete::Message& msg)
{
	kdWarning( 14160 ) << k_funcinfo << "m_account = " << m_account << " (should be non-zero!!)" << endl;
	if (!m_account) return;

	m_msg = msg;

	TDEConfigGroup* c = m_account->configGroup();
	TQString provider = c->readEntry(TQString("%1:%2").arg("SMSClient").arg("ProviderName"));

	if (provider.isNull())
	{
		KMessageBox::error(Kopete::UI::Global::mainWidget(), i18n("No provider configured"), i18n("Could Not Send Message"));
		return;
	}

	TQString programName = c->readEntry(TQString("%1:%2").arg("SMSClient").arg("ProgramName"));
	if (programName.isNull())
		programName = "/usr/bin/sms_client";

	TDEProcess* p = new TDEProcess;

	TQString message = msg.plainBody();
	TQString nr = msg.to().first()->contactId();

	*p << programName;
	*p << provider + ":" + nr;
	*p << message;

	TQObject::connect(p, TQT_SIGNAL(processExited(TDEProcess *)), this, TQT_SLOT(slotSendFinished(TDEProcess*)));
	TQObject::connect(p, TQT_SIGNAL(receivedStdout(TDEProcess*, char*, int)), this, TQT_SLOT(slotReceivedOutput(TDEProcess*, char*, int)));
	TQObject::connect(p, TQT_SIGNAL(receivedStderr(TDEProcess*, char*, int)), this, TQT_SLOT(slotReceivedOutput(TDEProcess*, char*, int)));

	p->start(TDEProcess::Block, TDEProcess::AllOutput);
}

TQWidget* SMSClient::configureWidget(TQWidget* parent)
{
	kdWarning( 14160 ) << k_funcinfo << "m_account = " << m_account << " (should be ok if zero!!)" << endl;

	if (prefWidget == 0L)
		prefWidget = new SMSClientPrefsUI(parent);

	prefWidget->configDir->setMode(KFile::Directory);
	TQString configDir;
	if (m_account)
		configDir = m_account->configGroup()->readEntry(TQString("%1:%2").arg("SMSClient").arg("ConfigDir"));
	if (configDir.isNull())
		configDir = "/etc/sms";
	prefWidget->configDir->setURL(configDir);

	TQString programName;
	if (m_account)
		programName = m_account->configGroup()->readEntry(TQString("%1:%2").arg("SMSClient").arg("ProgramName"));
	if (programName.isNull())
		programName = "/usr/bin/sms_client";
	prefWidget->program->setURL(programName);

	prefWidget->provider->insertStringList(providers());

	if (m_account)
	{
		TQString pName = m_account->configGroup()->readEntry(TQString("%1:%2").arg("SMSClient").arg("ProviderName"));
		for (int i=0; i < prefWidget->provider->count(); i++)
		{
			if (prefWidget->provider->text(i) == pName)
			{
				prefWidget->provider->setCurrentItem(i);
				break;
			}
		}
	}

	return prefWidget;
}

void SMSClient::savePreferences()
{
	kdWarning( 14160 ) << k_funcinfo << "m_account = " << m_account << " (should be work if zero!!)" << endl;

	if (prefWidget != 0L && m_account != 0L)
	{
		TDEConfigGroup* c = m_account->configGroup();

		c->writeEntry(TQString("%1:%2").arg("SMSClient").arg("ProgramName"), prefWidget->program->url());
		c->writeEntry(TQString("%1:%2").arg("SMSClient").arg("ConfigDir"), prefWidget->configDir->url());
		c->writeEntry(TQString("%1:%2").arg("SMSClient").arg("ProviderName"), prefWidget->provider->currentText());
	}
}

TQStringList SMSClient::providers()
{
	TQStringList p;

	TQDir d;
	d.setPath(TQString("%1/services/").arg(prefWidget->configDir->url()));
	p += d.entryList("*", TQDir::Files);

	return p;
}

void SMSClient::slotReceivedOutput(TDEProcess*, char  *buffer, int  buflen)
{
	TQStringList lines = TQStringList::split("\n", TQString::fromLocal8Bit(buffer, buflen));
	for (TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
		output.append(*it);
}

void SMSClient::slotSendFinished(TDEProcess* p)
{
	if (p->exitStatus() == 0)
		emit messageSent(m_msg);
	else
		emit messageNotSent(m_msg, output.join("\n"));
}

int SMSClient::maxSize()
{
	return 160;
}

const TQString& SMSClient::description()
{
	TQString url = "http://www.smsclient.org";
	m_description = i18n("<qt>SMSClient is a program for sending SMS with the modem. The program can be found on <a href=\"%1\">%1</a></qt>").arg(url).arg(url);
	return m_description;
}

#include "smsclient.moc"
