/*
 * This file is part of the KFTPGrabber project
 *
 * Copyright (C) 2003-2004 by the KFTPGrabber developers
 * Copyright (C) 2003-2004 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 "browser/view.h"
#include "browser/detailsview.h"
#include "browser/treeview.h"
#include "browser/actions.h"
#include "browser/filterwidget.h"

#include "kftpbookmarks.h"
#include "misc/kftpconfig.h"
#include "kftpsession.h"
#include "ftpsocket.h"

#include "misc.h"

#include <tdelocale.h>
#include <tdetoolbar.h>
#include <kstatusbar.h>
#include <kcombobox.h>
#include <tdeaction.h>
#include <tdemessagebox.h>
#include <ksslinfodlg.h>
#include <klineedit.h>
#include <kpixmapprovider.h>

#include <tdeio/job.h>

#include <tqdir.h>
#include <tqlabel.h>
#include <tqlayout.h>

using namespace KFTPGrabberBase;
using namespace KFTPEngine;

namespace KFTPWidgets {

namespace Browser {

class HistoryPixmapProvider : public KPixmapProvider
{
public:
    TQPixmap pixmapFor(const TQString&, int)
    {
      return loadSmallPixmap("folder");
    }
};

View::View(TQWidget *parent, const char *name, KFTPEngine::Thread *client, KFTPSession::Session *session)
 : TQWidget(parent, name),
   m_session(session),
   m_ftpClient(client)
{
  m_connTimer = new TQTimer(this);

  // Create the GUI
  init();
  populateToolbar();
  
  // Hide/show the tree acoording to configuration
  setTreeVisible(KFTPCore::Config::showTree());

  // Let us be up to date with bookmark changes
  connect(KFTPBookmarks::Manager::self(), TQ_SIGNAL(update()), this, TQ_SLOT(updateBookmarks()));
  
  // Some other stuff
  connect(m_ftpClient->eventHandler(), TQ_SIGNAL(engineEvent(KFTPEngine::Event*)), this, TQ_SLOT(slotEngineEvent(KFTPEngine::Event*)));
  connect(m_connTimer, TQ_SIGNAL(timeout()), this, TQ_SLOT(slotDurationUpdate()));
  
  // Config updates to hide/show the tree
  connect(KFTPCore::Config::self(), TQ_SIGNAL(configChanged()), this, TQ_SLOT(slotConfigUpdate()));
}

View::~View()
{
}

void View::init()
{
  // Init actions
  m_actions = new Actions(this);
  m_actions->initActions();

  // Layout
  TQVBoxLayout *layout = new TQVBoxLayout(this);

  // Create the toolbars
  m_toolBarFirst = new TDEToolBar(this, "first toolbar", false, false);
  m_toolBarSecond = new TDEToolBar(this, "second toolbar", false, false);
  m_searchToolBar = new TDEToolBar(this, "search toolbar", false, false);
  
  m_toolBarFirst->setEnableContextMenu(false);
  m_toolBarFirst->setMovingEnabled(false);
  m_toolBarFirst->setFullSize(true);

  m_toolBarSecond->setEnableContextMenu(false);
  m_toolBarSecond->setMovingEnabled(false);
  m_toolBarSecond->setFullSize(true);
  
  m_searchToolBar->setEnableContextMenu(false);
  m_searchToolBar->setMovingEnabled(false);
  m_searchToolBar->setFullSize(true);
  
  TQLabel *filterLabel = new TQLabel(i18n("Filter: "), m_searchToolBar);
  m_searchToolBar->insertWidget(1, 35, filterLabel);

  // Create the erase button
  m_toolBarSecond->insertButton(TQApplication::reverseLayout() ? "clear_left" :"locationbar_erase", 0, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotHistoryEraseClicked()), true);
  
  // Create the labels
  TQLabel *pathLabel = new TQLabel(i18n("Path: "), m_toolBarSecond);
  m_toolBarSecond->insertWidget(1, 35, pathLabel);

  // Create the history combo
  m_historyCombo = new KHistoryCombo(true, m_toolBarSecond);
  m_toolBarSecond->insertWidget(2, 0, m_historyCombo);
  m_historyCombo->setPixmapProvider(new HistoryPixmapProvider());
  m_historyCombo->setMaxCount(25);
  m_historyCombo->setSizeLimit(25);
  m_historyCombo->setDuplicatesEnabled(false);
  m_historyCombo->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed));
  
  connect(m_historyCombo, TQ_SIGNAL(activated(const TQString&)), this, TQ_SLOT(slotHistoryActivated(const TQString&)));

  // Do some more stuff
  m_toolBarSecond->setItemAutoSized(1, true);
  m_toolBarSecond->setStretchableWidget(m_historyCombo);
  m_toolBarSecond->updateRects(true);
  m_toolBarFirst->updateRects(true);

  // Create a splitter
  m_splitter = new TQSplitter(this);
  m_splitter->setOpaqueResize(true);
  m_splitter->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Expanding));

  // Create a status bar
  TQHBoxLayout *statusLayout = new TQHBoxLayout();

  m_connDurationMsg = new TQLabel(this);
  m_connDurationMsg->setAlignment(AlignAuto | AlignVCenter | AlignHCenter | ExpandTabs);
  m_connDurationMsg->setFrameStyle(TQFrame::StyledPanel | TQFrame::Sunken);
  m_connDurationMsg->setMinimumWidth(100);

  m_sslIcon = new TQPushButton(this);
  m_sslIcon->setFlat(true);
  m_sslIcon->setIconSet(SmallIconSet("decrypted"));
  m_sslIcon->setEnabled(false);

  connect(m_sslIcon, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotDisplayCertInfo()));

  m_statusMsg = new TQLabel(this);
  m_statusMsg->setFrameStyle(TQFrame::StyledPanel | TQFrame::Sunken);
  m_statusMsg->setText(i18n("Idle."));

  statusLayout->addWidget(m_statusMsg, 1);
  statusLayout->addWidget(m_connDurationMsg);
  statusLayout->addWidget(m_sslIcon);

  // Add toolbars to the layout
  layout->addWidget(m_toolBarFirst);
  layout->addWidget(m_toolBarSecond);
  layout->addWidget(m_splitter, 10);
  layout->addWidget(m_searchToolBar);
  layout->addLayout(statusLayout);

  // Now add some stuff to the splitter
  m_detailsView = new DetailsView(m_splitter, this, m_session);
  m_splitter->moveToLast(m_detailsView);
  
  connect(m_detailsView->locationNavigator(), TQ_SIGNAL(historyChanged()), this, TQ_SLOT(slotHistoryChanged()));

  // Create the tree view
  m_tree = new TreeView(m_splitter);
  m_splitter->moveToFirst(m_tree);

  m_detailsView->setTreeView(m_tree);
  m_detailsView->openUrl(KURL(KFTPCore::Config::defLocalDir()));
  
  // Create the filter widget
  m_searchFilter = new FilterWidget(m_searchToolBar, m_detailsView);
  m_searchToolBar->setItemAutoSized(2, true);
  m_searchToolBar->setStretchableWidget(m_searchFilter);
  
  m_searchToolBar->updateRects(true);
  m_searchToolBar->hide();
}

const KURL &View::url() const
{
  return m_detailsView->url();
}

const TQValueList<LocationNavigator::Element> View::history(int &index) const
{
  return m_detailsView->history(index);
}

const KFileItemList *View::selectedItems() const
{
  return m_detailsView->KFileView::selectedItems();
}

KURL::List View::selectedURLs() const
{
  KURL::List urls;
  const KFileItemList *list = selectedItems();
  
  if (list) {
    KFileItemListIterator i(*list);
    KFileItem *item;
    
    while ((item = i.current()) != 0) {
      urls.append(item->url());
      ++i;
    }
  }
  
  return urls;
}

const KFileItemList *View::items() const
{
  return m_detailsView->KFileView::items();
}

void View::openUrl(const KURL &url)
{
  m_detailsView->openUrl(url);
}

void View::setShowHidden(bool value)
{
  m_detailsView->setShowHidden(value);
}

void View::setHomeUrl(const KURL &url)
{
  m_detailsView->setHomeUrl(url);
}

void View::goBack()
{
  m_detailsView->goBack();
}
    
void View::goForward()
{
  m_detailsView->goForward();
}

void View::goUp()
{
  m_detailsView->goUp();
}

void View::goHome()
{
  m_detailsView->goHome();
}

void View::reload()
{
  m_detailsView->reload();
}

void View::rename(const KURL &source, const TQString &name)
{
  KURL dest(source.upURL());
  dest.addPath(name);
  
  if (source.isLocalFile())
    TDEIO::rename(source, dest, false); 
  else
    m_session->getClient()->rename(source, dest);
}

void View::slotConfigUpdate()
{
  setTreeVisible(KFTPCore::Config::showTree());
}

void View::setTreeVisible(bool visible)
{
  if (visible)
    m_tree->show();
  else
    m_tree->hide();
  
  m_actions->m_toggleTreeViewAction->setChecked(visible);
}

void View::populateToolbar()
{
  // Add the actions to the toolbar
  m_actions->m_siteChangeAction->plug(m_toolBarFirst);

  m_toolBarFirst->insertSeparator();

  m_actions->m_goUpAction->plug(m_toolBarFirst);
  m_actions->m_goBackAction->plug(m_toolBarFirst);
  m_actions->m_goForwardAction->plug(m_toolBarFirst);
  m_actions->m_reloadAction->plug(m_toolBarFirst);

  m_toolBarFirst->insertSeparator();

  m_actions->m_goHomeAction->plug(m_toolBarFirst);
  m_actions->m_createDirAction->plug(m_toolBarFirst);
  
  m_toolBarFirst->insertSeparator();
  
  m_actions->m_abortAction->plug(m_toolBarFirst);
  m_actions->m_toggleTreeViewAction->plug(m_toolBarFirst);
  m_actions->m_toggleFilterAction->plug(m_toolBarFirst);
  
  m_toolBarFirst->insertSeparator();
  
  m_actions->m_moreActions->plug(m_toolBarFirst);
}

void View::updateActions()
{
  // Force action update
  m_actions->updateActions();
}

void View::updateBookmarks()
{
  // Repopulate bookmarks menu on updates
  m_actions->m_connectAction->popupMenu()->clear();
  KFTPBookmarks::Manager::self()->guiPopulateBookmarksMenu(m_actions->m_connectAction, TQDomNode(), false, m_session);
}

void View::slotHistoryActivated(const TQString &text)
{
  KURL dest = url();
  dest.setPath(text);
  
  openUrl(dest);
}

void View::slotHistoryEraseClicked()
{
  m_historyCombo->setCurrentText(TQString::null);
  m_historyCombo->setFocus();
}

void View::slotHistoryChanged()
{
  /*m_historyCombo->insertItem(loadSmallPixmap("folder"), url().path(-1), 0);
  m_historyCombo->setCurrentItem(0);*/
  m_historyCombo->addToHistory(url().path(-1));
}

void View::slotDisplayCertInfo()
{
  if (m_ftpClient->socket()->protocolName() == "ftp" && m_ftpClient->socket()->isEncrypted()) {
    KSSLInfoDlg *sslInfo = new KSSLInfoDlg(true, this);
    sslInfo->exec();
  } else if (m_ftpClient->socket()->protocolName() == "sftp") {
    KMessageBox::information(this, i18n("This is a SSH encrypted connection. No certificate info is currently available."));
  } else {
    KSSLInfoDlg *sslInfo = new KSSLInfoDlg(false, this);
    sslInfo->exec();
  }
}

void View::slotDurationUpdate()
{
  m_connDuration = m_connDuration.addSecs(1);
  m_connDurationMsg->setText(m_connDuration.toString("hh:mm:ss"));
}

void View::slotEngineEvent(KFTPEngine::Event *event)
{
  switch (event->type()) {
    case Event::EventState: {
      // Set new state
      m_statusMsg->setText(event->getParameter(0).asString());
      break;
    }
    case Event::EventConnect:
    case Event::EventDisconnect: {
      // Change encryption icon
      m_sslIcon->setIconSet(SmallIconSet(m_ftpClient->socket()->isEncrypted() ? "encrypted" : "decrypted"));
      m_sslIcon->setEnabled(m_ftpClient->socket()->isConnected());
    
      // Start or stop the duration timer
      if (m_ftpClient->socket()->isConnected()) {
        m_connTimer->start(1000);
        m_connDuration.setHMS(0, 0, 0);
      } else {
        m_connTimer->stop();
        m_connDurationMsg->setText("");
      }
      
      // Reset selected charset to default
      TDEPopupMenu *menu = m_actions->m_changeEncodingAction->popupMenu();
      menu->setItemChecked(m_actions->m_defaultCharsetOption, true);
      menu->setItemChecked(m_actions->m_curCharsetOption, false);
      m_actions->m_curCharsetOption = m_actions->m_defaultCharsetOption;
      break;
    }
    default: break;
  }

  if (m_ftpClient->socket()->isBusy()) {
    m_tree->setEnabled(false);
    m_detailsView->setEnabled(false);
    m_toolBarSecond->setEnabled(false);
  } else if (KFTPQueue::Manager::self()->getNumRunning(m_ftpClient->socket()->getCurrentUrl()) == 0) {
    m_tree->setEnabled(true);
    m_detailsView->setEnabled(true);
    m_toolBarSecond->setEnabled(true);
  }
  
  // Update actions
  updateActions();
}

}

}

#include "view.moc"
