/* ============================================================
 * File   : uploadwidget.cpp
 * Authors: KIPI team developers (see AUTHORS files for details)
 *	    
 * Date   : 2004-02
 * Description :
 *
 * Copyright 2004 by the KIPI team
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Library General
 * Public License as published by the Free Software Foundation;
 * either version 2, 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 Library General Public License for more details.
 *
 * ============================================================ */

// TQt includes. 
  
#include <tqlayout.h>
#include <tqheader.h>
#include <tqlistview.h>
#include <tqdir.h>

// KDE includes

#include <kdebug.h>
#include <tdelocale.h>
#include <tdeio/jobclasses.h>
#include <tdemessagebox.h>
#include <kinputdialog.h>

// Local includes.

#include "uploadwidget.h"
#include "libkipi/imagecollection.h"


struct KIPI::UploadWidget::Private
{
    KFileTreeView* m_treeView;
    KFileTreeBranch* m_branch;
    TQStringList m_pendingPath;
};


/*!
  \class KIPI::UploadWidget
  This widget is used to specify an upload directory for new images.
*/

KIPI::UploadWidget::UploadWidget( KIPI::Interface* interface, TQWidget* parent, const char* name )
                  : TQWidget( parent, name )
{
    d = new Private;

    TQVBoxLayout* layout = new TQVBoxLayout( this, 0 );
    d->m_treeView = new KFileTreeView( this );
    d->m_treeView->setRootIsDecorated( true );
    layout->addWidget( d->m_treeView );

    // Fetch the current album, so we can start out there.
    KIPI::ImageCollection album = interface->currentAlbum();
    
    // If no current album selected, get the first album in the list.
    if ( !album.isValid() || !album.isDirectory() ) 
       album = interface->allAlbums().first();
    
    d->m_branch = d->m_treeView->addBranch( TQDir::cleanDirPath(album.uploadRoot().path()),
                                          album.uploadRootName() );
    d->m_treeView->setDirOnlyMode( d->m_branch, true );

    d->m_treeView->addColumn( i18n("Folder" ) );

    d->m_treeView->header()->setStretchEnabled( true, 0 );
    d->m_treeView->header()->hide();

    TQString root = album.uploadRoot().path();
    TQString uploadPath = album.isDirectory() ? album.uploadPath().path() : root;

    root       = TQDir::cleanDirPath(root);
    uploadPath = TQDir::cleanDirPath(uploadPath);
    
    if ( !uploadPath.startsWith( root ) ) 
    {
        kdWarning(51000) << "Error in Host application: uploadPath() should start with uploadRoot()." << endl
                         << "uploadPath() = " << album.uploadPath().prettyURL() << endl
                         << "uploadRoot() = " << album.uploadRoot().prettyURL() << endl;
    }
    else
    {
        uploadPath = uploadPath.mid( root.length() );
        
        d->m_pendingPath = TQStringList::split( "/", uploadPath, false );
        
        connect( d->m_branch, TQ_SIGNAL( populateFinished(KFileTreeViewItem *) ),
                 this, TQ_SLOT( slotPopulateFinished(KFileTreeViewItem *) ) );

        d->m_branch->setOpen(true);
    }
    
    connect( d->m_treeView, TQ_SIGNAL( executed(TQListViewItem *) ),
             this, TQ_SLOT( slotFolderSelected(TQListViewItem *) ) );
}

KIPI::UploadWidget::~UploadWidget()
{
    delete d;
}

KURL KIPI::UploadWidget::path() const
{
    return d->m_treeView->currentURL();
}

void KIPI::UploadWidget::load( )
{
    kdWarning() << "KIPI::UploadWidget::load(): This method is obsolete\n";
}

void KIPI::UploadWidget::slotPopulateFinished( KFileTreeViewItem * parentItem )
{
    if ( d->m_pendingPath.isEmpty() ) 
    {
        disconnect( d->m_branch, TQ_SIGNAL( populateFinished(KFileTreeViewItem *) ), 
                    this, TQ_SLOT( slotPopulateFinished(KFileTreeViewItem *) ) );
        return;
    }

    TQString itemName = d->m_pendingPath.front();

    d->m_pendingPath.pop_front();

    TQListViewItem * item;
    for ( item = parentItem->firstChild(); item; item = item->nextSibling() )
    {
        if ( item->text(0) == itemName )
        {
            break;
        }
    }
    
    if ( !item ) 
    {
        kdDebug( 51000 ) << "Unable to open " << itemName << endl;
    }
    else
    {
        item->setOpen( true );
        d->m_treeView->setSelected( item, true );
        d->m_treeView->ensureItemVisible ( item );
        
        KFileTreeViewItem * ftvItem = static_cast<KFileTreeViewItem *>( item );
        if ( ftvItem->alreadyListed() )
            slotPopulateFinished( ftvItem );
    }

}

void KIPI::UploadWidget::mkdir()
{
    if ( !path().isValid() ) 
        {
        KMessageBox::error( this, i18n("Please select a directory first.") );
        return;
        }

    bool ok;
    TQString dir = KInputDialog::getText( i18n("Create Directory"),
                                         i18n("<qt>Enter new directory name (to be created as subdir of %1):</qt>")
                                        .arg(path().prettyURL()), "", &ok, this);
    
    if (!ok) return;

    KURL url = path();
    url.addPath( dir );

    TDEIO::SimpleJob* job = TDEIO::mkdir(url);
    
    connect(job, TQ_SIGNAL(result(TDEIO::Job*)), 
            this, TQ_SLOT(slotAlbumCreated(TDEIO::Job*)));
}

void KIPI::UploadWidget::slotAlbumCreated(TDEIO::Job* job)
{
    int code = job->error();
    
    if ( code )
        job->showErrorDialog( this );
}

void KIPI::UploadWidget::slotFolderSelected(TQListViewItem *)
{
    emit folderItemSelected(d->m_treeView->currentURL());
}

#include "uploadwidget.moc"
