/*  This file is part of the KDE KMobile library
    Copyright (C) 2003 Helge Deller <deller@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 as published by the Free Software Foundation.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include <tqobject.h>

#include <kiconloader.h>
#include <klocale.h>
#include <kdebug.h>
#include <kconfig.h>

#include "kmobileitem.h"


#define PRINT_DEBUG kdDebug() << "KMobileItem: "

KMobileItem::KMobileItem(TQIconView *parent, KConfig *_config, KService::Ptr service)
	: TQObject(parent), TQIconViewItem(parent), m_dev(0L)
{
   config = _config;

   Q_CHECK_PTR(service);
   if (service) {
	setText(service->name());
	m_deviceDesktopFile = service->desktopEntryName();
	m_deviceConfigFile = TQString("kmobile_%1_rc").arg(text());
	m_deviceConfigFile = m_deviceConfigFile.replace(' ', "");
	m_iconName = service->icon();
   };

   if (m_iconName.isEmpty())
        m_iconName = KMOBILE_ICON_UNKNOWN;

   setPixmap(getIcon());
   setRenameEnabled(true);
}

/* restore this item from the config file */
KMobileItem::KMobileItem(TQIconView *parent, KConfig *_config, int reload_index)
	: TQObject(parent), TQIconViewItem(parent), m_dev(0L)
{
   config = _config;

   if (!configLoad(reload_index)) {
	delete this;
	return;
   }

   setPixmap(getIcon());
   setRenameEnabled(true);
}

KMobileItem::~KMobileItem()
{
   delete m_dev;
}


void KMobileItem::configSave() const
{
   config->setGroup( config_SectionName() );
   config->writeEntry( "Name", text() );
   config->writeEntry( "Config", m_deviceConfigFile );
   config->writeEntry( "DesktopFile", m_deviceDesktopFile );
   config->writeEntry( "IconName", m_iconName );
   config->sync();
}

bool KMobileItem::configLoad(int idx)
{
   config->setGroup( config_SectionName(idx) );
   setText( config->readEntry("Name") );
   m_deviceConfigFile	= config->readEntry( "Config" );
   m_deviceDesktopFile	= config->readEntry( "DesktopFile" );
   m_iconName		= config->readEntry( "IconName" );

   if (text().isEmpty() || m_deviceConfigFile.isEmpty() ||
	m_deviceDesktopFile.isEmpty() || m_iconName.isEmpty() )
	return false;

   return true;
}

TQPixmap KMobileItem::getIcon() const
{
   return KGlobal::instance()->iconLoader()->loadIcon(m_iconName, KIcon::Desktop );
}

TQString KMobileItem::config_SectionName(int idx) const
{
   if (idx == -1) idx = index();
   return TQString("MobileDevice_%1").arg(idx);
}

/* this MimeType is used by konqueror */
TQString KMobileItem::getKonquMimeType() const
{
   return KMOBILE_MIMETYPE_DEVICE_KONTQUEROR(text());
}

/* provide MimeType for konqueror */
void KMobileItem::writeKonquMimeFile() const
{
   // strip path and file extension of icon name
   TQString icon = m_iconName;
   int p = icon.findRev('/');
   if (p>=0) icon = icon.mid(p+1);
   p = icon.find('.');
   if (p>=0) icon = icon.left(p);

   TQString comment;
   if (m_dev)
	comment = m_dev->deviceClassName();
   if (comment.isEmpty())
	comment = KMobileDevice::defaultClassName(KMobileDevice::Unclassified);

   KConfig conf( getKonquMimeType()+".desktop", false, true, "mime" );
   conf.setDesktopGroup();
   conf.writeEntry("Encoding", "UTF-8");
   conf.writeEntry("Comment", comment );
   conf.writeEntry("Type", "MimeType");
   conf.writeEntry("Icon", icon );
   conf.writeEntry("MimeType", getKonquMimeType());
   conf.writeEntry("Patterns", "" );
   conf.sync();
}


/*
 * get a list of all services providing a libkmobile device driver
 */
KTrader::OfferList KMobileItem::getMobileDevicesList()
{
  KTrader::OfferList offers = KTrader::self()->query(KMOBILE_MIMETYPE_DEVICE);
  return offers;
}


KService::Ptr KMobileItem::getServicePtr() const
{
  KTrader::OfferList list = getMobileDevicesList();
  KTrader::OfferListIterator it;
  KService::Ptr ptr;
  for ( it = list.begin(); it != list.end(); ++it ) {
    KService::Ptr ptr = *it;
    if (ptr->desktopEntryName() == m_deviceDesktopFile)
 	return ptr;
  }
  PRINT_DEBUG << TQString("Service for library '%1' not found in KService list\n")
			.arg(m_deviceDesktopFile);
  return 0L;
}

/*
 * loads & initializes the device and returns a pointer to it.
 */
bool KMobileItem::driverAvailable()
{
   if (m_dev)
	return true;

   KService::Ptr ptr = getServicePtr();
   if (!ptr)
	return false;

   PRINT_DEBUG << TQString("Loading library %1\n").arg(ptr->library());
   KLibFactory *factory = KLibLoader::self()->factory( ptr->library().utf8() );
   if (!factory)
	return false;

   m_dev = static_cast<KMobileDevice *>(factory->create(this, ptr->name().utf8(),
				"KMobileDevice", TQStringList(m_deviceConfigFile)));
   PRINT_DEBUG << TQString("Got KMobileDevice object at 0x%1, configfile=%2\n")
			.arg((unsigned long)m_dev, 0, 16).arg(m_deviceConfigFile);

   return (m_dev != 0);
}

#include "kmobileitem.moc"