/***************************************************************************
                         directorylist.cpp
                            -------------------
   begin                : Tue Feb 4 2003
   copyright            : (C) 2003 Scott Wheeler <wheeler@kde.org>
                        : (C) 2004 Max Howell <max.howell@methylblue.com>
                        : (C) 2004 Mark Kretschmann <markey@web.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 <qlabel.h>
#include <qtooltip.h>
#include <qdir.h>

#include <kfileitem.h>
#include <klocale.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <qregexp.h>
#include <kiconloader.h>
#include <kapplication.h>
#include <dcopref.h>
#include <dcopclient.h>
#include <kautomount.h>

#include "directorylist.h"

using Collection::Item;
using Collection::DeviceItem;

CollectionSetup* CollectionSetup::s_instance;


CollectionSetup::CollectionSetup( QWidget *parent, bool recursive )
    : QVBox( parent )
{
    s_instance = this;

//     (new QLabel( i18n(
//         "Select the folder(s) to scan. "), this ))->setAlignment( Qt::WordBreak );

    m_view = new QListView( this );
/*     m_recursive = new QCheckBox( i18n("&Scan folders recursively"), this );*/
    m_recursive = recursive;
//     m_monitor   = new QCheckBox( i18n("&Watch folders for changes"), this );
//     m_playlists = new QCheckBox( i18n("&Import playlists"), this );
// 
//     QToolTip::add( m_recursive, i18n( "If selected, amaroK reads all folders recursively." ) );
//     QToolTip::add( m_monitor,   i18n( "If selected, folders will automatically get rescanned when the content is modified, e.g. when a new file was added." ) );
//     QToolTip::add( m_playlists, i18n( "If selected, playlist files (.m3u) will automatically be added to the Playlist-Browser." ) );

    // Read config values
//     m_dirs = AmarokConfig::collectionFolders();
//     m_recursive->setChecked( false );
//     m_monitor->setChecked( AmarokConfig::monitorChanges() );
//     m_playlists->setChecked( AmarokConfig::importPlaylists() );

    m_view->addColumn( QString::null );
    m_view->setRootIsDecorated( true );
    reinterpret_cast<QWidget*>(m_view->header())->hide();
    new Item(  m_view, i18n( "System Folder" ), "/", "folder_red" );
    new Item(  m_view, i18n( "Home Folder" ), QDir::homeDirPath(), "folder_home" );
    new DeviceItem(  m_view );
    
    setSpacing( 6 );
}

void CollectionSetup::slotRecursiveToggled(bool on)
{
	m_recursive = on;
}


//////////////////////////////////////////////////////////////////////////////////////////
// CLASS Item
//////////////////////////////////////////////////////////////////////////////////////////
Item::Item(  QListView *parent , const QString &name, const QString &path, const QString &icon )
    : QCheckListItem(  parent, name, QCheckListItem::CheckBox  )
    , m_lister( true )
    , m_url( "file:" + path )
    , m_listed( false )
{
    m_lister.setDirOnlyMode( true );
    m_lister.setShowingDotFiles( true );
    connect( &m_lister, SIGNAL(newItems( const KFileItemList& )), SLOT(newItems( const KFileItemList& )) );
    setText( 1, path );
    setOpen( true );
    if (  !icon.isNull() )
       setPixmap(  0, SmallIcon( icon ) );
    else
       setPixmap(  0, SmallIcon( "folder" ) );
    setVisible( true );
}


Item::Item( QListViewItem *parent, const KURL &url )
    : QCheckListItem( parent, url.fileName(), QCheckListItem::CheckBox  )
    , m_lister( true )
    , m_url( url )
    , m_listed( false )
{
    m_lister.setDirOnlyMode( true );
    m_lister.setShowingDotFiles( true );
    setText( 1, url.fileName() );
    setExpandable( true );
    connect( &m_lister, SIGNAL(newItems( const KFileItemList& )), SLOT(newItems( const KFileItemList& )) );
    connect( &m_lister, SIGNAL(completed()), SLOT(completed()) );
    connect( &m_lister, SIGNAL(canceled()), SLOT(completed()) );
}


QString
Item::fullPath() const
{
   QString path;
   
   for (  const QListViewItem *item = this; dynamic_cast<const QListViewItem*>( item ); item = item->parent() )
   {
      path.prepend( '/' );
      path.prepend(  item->text(  1 ) );
   }
   return path;
}


void
Item::setOpen( bool b )
{
    if ( !m_listed )
    {
        m_lister.openURL( m_url, true );
        m_listed = true;
    }

    QListViewItem::setOpen( b );
}


void
Item::stateChange( bool b )
{
    if( CollectionSetup::instance()->recursive() )
        for( QListViewItem *item = firstChild(); item; item = item->nextSibling() )
            static_cast<QCheckListItem*>(item)->QCheckListItem::setOn( b );

    // Update folder list
    QStringList::Iterator it = CollectionSetup::instance()->m_dirs.find( m_url.path() );
    if ( isOn() ) {
        if ( it == CollectionSetup::instance()->m_dirs.end() )
        {
            CollectionSetup::instance()->m_dirs << m_url.path();
            CollectionSetup::instance()->m_refcount[ m_url.path() ] = 1;
        }
        else
           CollectionSetup::instance()->m_refcount[ m_url.path() ]++;
    }
    else if ( CollectionSetup::instance()->m_refcount.find( m_url.path() ) != CollectionSetup::instance()->m_refcount.end() )
    {
       if ( --CollectionSetup::instance()->m_refcount[ m_url.path() ] == 0 )
       {
          CollectionSetup::instance()->m_dirs.erase(  it );
          CollectionSetup::instance()->m_refcount.remove( m_url.path() );
       }
    }

    // Redraw parent items
    listView()->triggerUpdate();
}


void
Item::activate()
{
    if( !isDisabled() )
        QCheckListItem::activate();
}


void
Item::newItems( const KFileItemList &list ) //SLOT
{
    for( KFileItemListIterator it( list ); *it; ++it )
    {
        Item *item = new Item( this, (*it)->url() );

        item->setOn( CollectionSetup::instance()->recursive() && isOn() ||
                     CollectionSetup::instance()->m_dirs.contains( item->fullPath() ) );

        item->setPixmap( 0, (*it)->pixmap( KIcon::SizeSmall ) );
    }
}


void
Item::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int align )
{
    bool dirty = false;

    // Figure out if a child folder is activated
    for ( uint i = 0; i < CollectionSetup::instance()->m_dirs.count(); i++ )
    {
       if (  CollectionSetup::instance()->m_dirs[ i ] == m_url.path() )
       {
          dirty = true;
       }
       else if (  CollectionSetup::instance()->m_dirs[ i ].startsWith(  m_url.path() ) )
          dirty = true;
    }

    // Use a different color if this folder has an activated child folder
    QColorGroup _cg = cg;
    if ( dirty ) _cg.setColor( QColorGroup::Text, Qt::blue );

    QCheckListItem::paintCell( p, isDisabled() ? listView()->palette().disabled() : _cg, column, width, align );
    if (!dirty)
        setOn(false);
}

//////////////////////////////////////////////////////////////////////////////////////////
// CLASS DeviceItem
//////////////////////////////////////////////////////////////////////////////////////////

DeviceItem::DeviceItem( QListView *parent )
    : QCheckListItem( parent, i18n("Devices"), QCheckListItem::CheckBox  )
    , m_lister( true )
    , m_listed( false )
{
    m_lister.setDirOnlyMode( true );
    connect( &m_lister, SIGNAL(newItems( const KFileItemList& )), SLOT(newItems( const KFileItemList& )) );

    if ( KDE::versionMajor() == 3 && KDE::versionMinor() < 4 )
    {
       m_url = "devices:/";
    }
    else
       m_url = "media:/";

    setText(1, "devices");
    setOpen( true );
    setPixmap(0, SmallIcon("kfm") );
    setVisible( true );
}


DeviceItem::DeviceItem( QListViewItem *parent, const QString &name, const KURL &url )
    : QCheckListItem( parent, name, QCheckListItem::CheckBox  )
    , m_lister( true )
    , m_url( url )
    , m_listed( false )
{

    if (!kapp->dcopClient()->isAttached())
        kapp->dcopClient()->attach();
    else
		////kdDebug() << "attached" << endl;

    QByteArray data;
    QByteArray param;
    QCString retType;
    QStringList retVal;
    QDataStream streamout(param,IO_WriteOnly);
    streamout<< url.fileName();
    QCString mediacall="mediamanager";
    QCString devicecall="properties";
    if ( KDE::versionMajor() == 3 && KDE::versionMinor() < 4 )
    {
       mediacall="mountwatcher";
       devicecall="basicDeviceInfo";
    }
    

	DCOPRef mediamanager("kded", mediacall);
	DCOPReply reply = mediamanager.call( devicecall, url.fileName() );

    if ( !reply.isValid() )
    {
            ////kdDebug() << "not valid" << endl;
    }
    retVal = reply;
    //KAutoMount* am = new KAutoMount( true, "", retVal[5], "","", false );
    ////kdDebug() << retVal[6] << endl;
    
    setText(1, KURL(retVal[6]).path());
	setText(2, url.fileName());
    //kdDebug() << "Device Item: " << name << " " << url.fileName() << " " << text(1) << endl;
    m_lister.setDirOnlyMode( true );
    setExpandable( false );
    connect( &m_lister, SIGNAL(newItems( const KFileItemList& )), SLOT(newItems( const KFileItemList& )) );
    connect( &m_lister, SIGNAL(completed()), SLOT(completed()) );
    connect( &m_lister, SIGNAL(canceled()), SLOT(completed()) );
}


QString
DeviceItem::fullPath() const
{
    QString path = text(1);
    if (path != "devices")
        return path;
    return "";
}


void
DeviceItem::setOpen( bool b )
{
    if ( !m_listed  && text(1) == "devices")
    {
        m_lister.openURL( m_url, true );
    }
    m_listed = true;

    QListViewItem::setOpen( b );
}


void
DeviceItem::stateChange( bool b )
{
    if( CollectionSetup::instance()->recursive() )
        for( QListViewItem *item = firstChild(); item; item = item->nextSibling() )
            static_cast<QCheckListItem*>(item)->QCheckListItem::setOn( b );
    
    if (text(1) != "devices")
    {
        // Update folder list
        QStringList::Iterator it = CollectionSetup::instance()->m_dirs.find( text(1) );
        if ( isOn() ) {
            if ( it == CollectionSetup::instance()->m_dirs.end() )
            {
                CollectionSetup::instance()->m_dirs << text(1);
				mountDevice(text(2));
                CollectionSetup::instance()->m_refcount[text(1)] = 1;
            }
            else
                 CollectionSetup::instance()->m_refcount[text(1)]++;

        }
        else if ( CollectionSetup::instance()->m_refcount.find(text(1)) != CollectionSetup::instance()->m_refcount.end() )
        {
            if ( --CollectionSetup::instance()->m_refcount[text(1)] == 0 )
            {
                CollectionSetup::instance()->m_dirs.erase( it );
	            CollectionSetup::instance()->m_refcount.remove(text(1));
            }
        }
    } 

    // Redraw parent items
    listView()->triggerUpdate();
}


void
DeviceItem::activate()
{
    if( !isDisabled() )
        QCheckListItem::activate();
}


void
DeviceItem::newItems( const KFileItemList &list ) //SLOT
{
    for( KFileItemListIterator it( list ); *it; ++it )
    {
        ////kdDebug() << (*it)->name() << " " << (*it)->url() << " " << (*it)->text() << endl;
        if (this->listView()->findItem((*it)->name(),0) == 0){
            DeviceItem *item = new DeviceItem( this, (*it)->name(), (*it)->url() );

            item->setOn( CollectionSetup::instance()->recursive() && isOn() ||
                        CollectionSetup::instance()->m_dirs.contains( item->fullPath() ) );
    
            item->setPixmap( 0, (*it)->pixmap( KIcon::SizeSmall ) );
        }
    }
}


void
DeviceItem::paintCell( QPainter * p, const QColorGroup & cg, int column, int width, int align )
{
   bool dirty = false;
   
   QColorGroup _cg = cg;

	////kdDebug() << text(1) << endl;
   if (text(1) != "devices")
   {
      // Figure out if a child folder is activated
      for ( uint i = 0; i < CollectionSetup::instance()->m_dirs.count(); i++ )
      {
         if ( CollectionSetup::instance()->m_dirs[i] == text(1) )
         {
            dirty = true;
         }
         else if ( CollectionSetup::instance()->m_dirs[i].startsWith( text(1) + "/" ) )
            dirty = true;
      }

   }
   else
   {
      for( QListViewItem *item = firstChild(); item; item = item->nextSibling() )
      {
         DeviceItem *itm = dynamic_cast<DeviceItem*>(item);
         for ( uint i = 0; i < CollectionSetup::instance()->m_dirs.count(); i++ )
         {
            if ( CollectionSetup::instance()->m_dirs[i] == itm->fullPath() )
            {
               dirty = true;
               break;
            }
            else if ( CollectionSetup::instance()->m_dirs[i].startsWith( itm->fullPath() ) )
            {
               dirty = true;
               break;
            }
         }
      }
   }
   // Use a different color if this folder has an activated child folder
   if ( dirty ) _cg.setColor( QColorGroup::Text, Qt::blue );
   QCheckListItem::paintCell( p, isDisabled() ? listView()->palette().disabled() : _cg, column, width, align );
}

void
DeviceItem::mountDevice( const QString & device)
{

    if (!kapp->dcopClient()->isAttached())
        kapp->dcopClient()->attach();


	//Set Up our DCOP Calls

    QStringList retVal;
    QCString mediacall="mediamanager";
    QCString devicecall="properties";
    if ( KDE::versionMajor() == 3 && KDE::versionMinor() < 4 )
    {
       mediacall="mountwatcher";
       devicecall="basicDeviceInfo";
    }
    
	
	//Mount any devices that are not already mounted

	DCOPRef mediamanager("kded", mediacall);
	DCOPReply reply = mediamanager.call( devicecall, device );

	if ( !reply.isValid() )
	{
		////kdDebug() << "not valid" << endl;
	}
	retVal = reply;
	////kdDebug() << retVal << endl;
	////kdDebug() << retVal[1] << endl;
	////kdDebug() << retVal[10] << endl;
	if (!(retVal[10].contains("_mounted")))
		new KAutoMount( true, "", retVal[5], "","", false );
}



#include "directorylist.moc"
