/*
 * This file is part of the KFTPGrabber project
 *
 * Copyright (C) 2003-2006 by the KFTPGrabber developers
 * Copyright (C) 2003-2006 Jernej Kos <kostko@jweb-network.net>
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful, but
 * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
 * NON-INFRINGEMENT.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 *
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
#include "dirlister.h"

#include "engine/thread.h"
#include "engine/cache.h"

#include "kftpsession.h"

#include <kmessagebox.h>
#include <klocale.h>

using namespace KFTPEngine;

namespace KFTPWidgets {

namespace Browser {

DirLister::DirLister(QObject *parent)
  : QObject(parent)
{
  m_localLister = new KDirLister();
  m_localLister->setAutoUpdate(true);
  
  enableLocal();
}

DirLister::~DirLister()
{
  delete m_localLister;
}

void DirLister::setSession(KFTPSession::Session *session)
{
  m_remoteSession = session;
}

void DirLister::fetchLocation(const KURL &url, bool reload)
{
  if (m_url.isLocalFile() != url.isLocalFile())
    emit siteChanged(url);
  
  m_url = url;
  
  if (url.isLocalFile()) {
    enableLocal();
    
    m_localLister->stop();
    m_localLister->setShowingDotFiles(m_showHidden);
    m_localLister->openURL(url, false, reload);
  } else {
    enableRemote();
    
    if (reload) {
      KURL tmp = url;
      Cache::self()->invalidateEntry(tmp);
    }
    
    emit clear();
    m_remoteSession->getClient()->list(url);
  }
}

void DirLister::enableLocal()
{
  m_localLister->stop();
  m_localLister->QObject::disconnect(this);
  
  connect(m_localLister, SIGNAL(clear()), this, SIGNAL(clear()));
  connect(m_localLister, SIGNAL(completed()), this, SIGNAL(completed()));
  connect(m_localLister, SIGNAL(deleteItem(KFileItem*)), this, SIGNAL(deleteItem(KFileItem*)));
  connect(m_localLister, SIGNAL(refreshItems(const KFileItemList&)), this, SIGNAL(refreshItems()));
}

void DirLister::enableRemote()
{
  m_localLister->stop();
  m_localLister->QObject::disconnect(this);
  m_remoteSession->getClient()->eventHandler()->QObject::disconnect(this);
  
  connect(m_remoteSession->getClient()->eventHandler(), SIGNAL(engineEvent(KFTPEngine::Event*)), this, SLOT(slotRemoteEngineEvent(KFTPEngine::Event*)));
}

void DirLister::disableRemote()
{
  m_remoteSession->getClient()->eventHandler()->QObject::disconnect(this);
}

void DirLister::stop()
{
  if (m_url.isLocalFile())
    m_localLister->stop();
}

KFileItemList DirLister::items() const
{
  if (m_url.isLocalFile())
    return m_localLister->items();
  else
    return m_items;
}

void DirLister::slotRemoteEngineEvent(KFTPEngine::Event *event)
{
  switch (event->type()) {
    case Event::EventError: {
      KMessageBox::error(0, i18n("Could not enter folder %1.").arg(m_url.path()), i18n("Error"));
      disableRemote();
      break;
    }
    case Event::EventDirectoryListing: {
      m_items.clear();
      
      // Populate the item list
      QValueList<DirectoryEntry> list = event->getParameter(0).asDirectoryListing().list();
      QValueList<DirectoryEntry>::ConstIterator end(list.end());
      for (QValueList<DirectoryEntry>::ConstIterator i(list.begin()); i != end; ++i) {
        if (!m_showHidden && (*i).filename().at(0) == '.')
          continue;
        
        m_items.append(new KFileItem((*i).toUdsEntry(), m_url, false, true));
      }
      
      disableRemote();
      emit completed();
      break;
    }
    default: break;
  }
}

}

}

#include "dirlister.moc"
