/* This file is part of the KDE project
   Copyright (C) 2005 Peter Simonsson <psn@linux.se>

   This library 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 of the License, or (at your option) any later version.

   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 "KoDetailsPane.h"

#include <tqcheckbox.h>
#include <tqlabel.h>
#include <tqfile.h>
#include <tqimage.h>
#include <tqheader.h>
#include <tqrect.h>
#include <tqbrush.h>
#include <tqpainter.h>
#include <tqsimplerichtext.h>
#include <tqevent.h>
#include <tqsplitter.h>

#include <kinstance.h>
#include <tdelocale.h>
#include <tdelistview.h>
#include <kpushbutton.h>
#include <tdeconfig.h>
#include <kurl.h>
#include <tdefileitem.h>
#include <tdeio/previewjob.h>
#include <kdebug.h>
#include <ktextbrowser.h>
#include <tdeapplication.h>

#include "KoTemplates.h"

class KoFileListItem : public TDEListViewItem
{
  public:
    KoFileListItem(TDEListView* listView, TQListViewItem* after, const TQString& filename,
                   const TQString& fullPath, KFileItem* fileItem)
      : TDEListViewItem(listView, after, filename, fullPath), m_fileItem(fileItem)
    {
    }

    ~KoFileListItem()
    {
      delete m_fileItem;
    }

    KFileItem* fileItem() const
    {
      return m_fileItem;
    }

  private:
    KFileItem* m_fileItem;
};

class KoTemplatesPanePrivate
{
  public:
    KoTemplatesPanePrivate()
      : m_instance(0), m_selected(false)
    {
    }

    TDEInstance* m_instance;
    bool m_selected;
    TQString m_alwaysUseTemplate;
};


KoTemplatesPane::KoTemplatesPane(TQWidget* parent, TDEInstance* instance,
                                 KoTemplateGroup *group, KoTemplate* /*defaultTemplate*/)
  : KoDetailsPaneBase(parent, "TemplatesPane")
{
  d = new KoTemplatesPanePrivate;
  d->m_instance = instance;
  m_previewLabel->installEventFilter(this);
  m_documentList->installEventFilter(this);
  setFocusProxy(m_documentList);
#if KDE_IS_VERSION(3,4,0)
  m_documentList->setShadeSortColumn(false);
#endif

  KGuiItem openGItem(i18n("Use This Template"));
  m_openButton->setGuiItem(openGItem);
  m_documentList->header()->hide();
  TDEConfigGroup cfgGrp(d->m_instance->config(), "TemplateChooserDialog");
  TQString fullTemplateName = cfgGrp.readPathEntry("FullTemplateName");
  d->m_alwaysUseTemplate = cfgGrp.readPathEntry("AlwaysUseTemplate");
  connect(m_alwaysUseCheckBox, TQT_SIGNAL(clicked()), this, TQT_SLOT(alwaysUseClicked()));
  changePalette();

  if(kapp) {
    connect(kapp, TQT_SIGNAL(tdedisplayPaletteChanged()), this, TQT_SLOT(changePalette()));
  }

  TDEListViewItem* selectItem = 0;

  for (KoTemplate* t = group->first(); t != 0L; t = group->next()) {
    TDEListViewItem* item = new TDEListViewItem(m_documentList, t->name(), t->description(), t->file());
    TQImage icon = t->loadPicture(instance).convertToImage();
    icon = icon.smoothScale(64, 64, TQ_ScaleMin);
    icon.setAlphaBuffer(true);
    icon = icon.copy((icon.width() - 64) / 2, (icon.height() - 64) / 2, 64, 64);
    item->setPixmap(0, TQPixmap(icon));
    item->setPixmap(2, t->loadPicture(instance));

    if(d->m_alwaysUseTemplate == t->file()) {
      selectItem = item;
    } else if(!selectItem && (t->file() == fullTemplateName)) {
      selectItem = item;
    }
  }

  connect(m_documentList, TQT_SIGNAL(selectionChanged(TQListViewItem*)),
          this, TQT_SLOT(selectionChanged(TQListViewItem*)));
  connect(m_documentList, TQT_SIGNAL(doubleClicked(TQListViewItem*, const TQPoint&, int)),
          this, TQT_SLOT(openTemplate(TQListViewItem*)));
  connect(m_documentList, TQT_SIGNAL(returnPressed(TQListViewItem*)),
          this, TQT_SLOT(openTemplate(TQListViewItem*)));
  connect(m_openButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(openTemplate()));

  if(selectItem) {
    m_documentList->setSelected(selectItem, true);
    d->m_selected = true;
  } else {
    m_documentList->setSelected(m_documentList->firstChild(), true);
  }
}

KoTemplatesPane::~KoTemplatesPane()
{
  delete d;
}

void KoTemplatesPane::selectionChanged(TQListViewItem* item)
{
  if(item) {
    m_openButton->setEnabled(true);
    m_alwaysUseCheckBox->setEnabled(true);
    m_titleLabel->setText(item->text(0));
    m_previewLabel->setPixmap(*(item->pixmap(2)));
    m_detailsLabel->setText(item->text(1));
    m_alwaysUseCheckBox->setChecked(item->text(2) == d->m_alwaysUseTemplate);
  } else {
    m_openButton->setEnabled(false);
    m_alwaysUseCheckBox->setEnabled(false);
    m_alwaysUseCheckBox->setChecked(false);
    m_titleLabel->setText(TQString());
    m_previewLabel->setPixmap(TQPixmap());
  }
}

void KoTemplatesPane::openTemplate()
{
  TQListViewItem* item = m_documentList->selectedItem();
  openTemplate(item);
}

void KoTemplatesPane::openTemplate(TQListViewItem* item)
{
  if(item) {
    TDEConfigGroup cfgGrp(d->m_instance->config(), "TemplateChooserDialog");
    cfgGrp.writePathEntry("FullTemplateName", item->text(2));
    cfgGrp.writeEntry("LastReturnType", "Template");
    cfgGrp.writeEntry("AlwaysUseTemplate", d->m_alwaysUseTemplate);
    emit openTemplate(item->text(2));
  }
}

void KoTemplatesPane::changePalette()
{
  TQPalette p = kapp ? kapp->palette() : palette();
  p.setBrush(TQColorGroup::Base, p.brush(TQPalette::Normal, TQColorGroup::Background));
  p.setColor(TQColorGroup::Text, p.color(TQPalette::Normal, TQColorGroup::Foreground));
  m_detailsLabel->setPalette(p);
}

bool KoTemplatesPane::isSelected()
{
  return d->m_selected;
}

void KoTemplatesPane::alwaysUseClicked()
{
  TQListViewItem* item = m_documentList->selectedItem();

  if(!m_alwaysUseCheckBox->isChecked()) {
    TDEConfigGroup cfgGrp(d->m_instance->config(), "TemplateChooserDialog");
    cfgGrp.writeEntry("AlwaysUseTemplate", TQString());
    d->m_alwaysUseTemplate = TQString();
  } else {
    d->m_alwaysUseTemplate = item->text(2);
  }

  emit alwaysUseChanged(this, d->m_alwaysUseTemplate);
}

void KoTemplatesPane::changeAlwaysUseTemplate(KoTemplatesPane* sender, const TQString& alwaysUse)
{
  if(this == sender)
    return;

  TQListViewItem* item = m_documentList->selectedItem();

  // If the old always use template is selected uncheck the checkbox
  if(item && (item->text(2) == d->m_alwaysUseTemplate)) {
    m_alwaysUseCheckBox->setChecked(false);
  }

  d->m_alwaysUseTemplate = alwaysUse;
}

bool KoTemplatesPane::eventFilter(TQObject* watched, TQEvent* e)
{
  if(TQT_BASE_OBJECT(watched) == m_previewLabel) {
    if(e->type() == TQEvent::MouseButtonDblClick) {
      openTemplate();
    }
  }

  if(TQT_BASE_OBJECT(watched) == m_documentList) {
    if((e->type() == TQEvent::Resize) && isShown()) {
      emit splitterResized(this, m_splitter->sizes());
    }
  }

  return false;
}

void KoTemplatesPane::resizeSplitter(KoDetailsPaneBase* sender, const TQValueList<int>& sizes)
{
  if(sender == this)
    return;

  m_splitter->setSizes(sizes);
}


class KoRecentDocumentsPanePrivate
{
  public:
    KoRecentDocumentsPanePrivate()
      : m_previewJob(0), m_instance(0)
    {
    }

    ~KoRecentDocumentsPanePrivate()
    {
      if(m_previewJob)
        m_previewJob->kill();
    }

    TDEIO::PreviewJob* m_previewJob;
    TDEInstance* m_instance;
};

KoRecentDocumentsPane::KoRecentDocumentsPane(TQWidget* parent, TDEInstance* instance)
  : KoDetailsPaneBase(parent, "RecentDocsPane")
{
  d = new KoRecentDocumentsPanePrivate;
  d->m_instance = instance;
  m_previewLabel->installEventFilter(this);
  m_documentList->installEventFilter(this);
  setFocusProxy(m_documentList);
  KGuiItem openGItem(i18n("Open This Document"), "document-open");
  m_openButton->setGuiItem(openGItem);
  m_alwaysUseCheckBox->hide();
  m_documentList->header()->hide();
  m_documentList->setSorting(-1); // Disable sorting
  changePalette();

  if(kapp) {
    connect(kapp, TQT_SIGNAL(tdedisplayPaletteChanged()), this, TQT_SLOT(changePalette()));
  }

  TQString oldGroup = instance->config()->group();
  instance->config()->setGroup("RecentFiles");

  int i = 0;
  TQString value;
  KFileItemList fileList;
  fileList.setAutoDelete(false);

  do {
    TQString key = TQString("File%1").arg(i);
    value = instance->config()->readPathEntry(key);

    if(!value.isEmpty()) {
      TQString path = value;
      TQString name;

      // Support for tdelibs-3.5's new RecentFiles format: name[url]
      if(path.endsWith("]")) {
        int pos = path.find("[");
        name = path.mid(0, pos - 1);
        path = path.mid(pos + 1, path.length() - pos - 2);
      }

      KURL url(path);

      if(name.isEmpty())
        name = url.filename();

      if(!url.isLocalFile() || TQFile::exists(url.path())) {
        KFileItem* fileItem = new KFileItem(KFileItem::Unknown, KFileItem::Unknown, url);
        fileList.append(fileItem);
        KoFileListItem* item = new KoFileListItem(m_documentList,
            m_documentList->lastItem(), name, url.url(), fileItem);
        //center all icons in 64x64 area
        TQImage icon = fileItem->pixmap(64).convertToImage();
        icon.setAlphaBuffer(true);
        icon = icon.copy((icon.width() - 64) / 2, (icon.height() - 64) / 2, 64, 64);
        item->setPixmap(0, TQPixmap(icon));
        item->setPixmap(2, fileItem->pixmap(128));
      }
    }

    i++;
  } while ( !value.isEmpty() || i<=10 );

  instance->config()->setGroup( oldGroup );

  connect(m_documentList, TQT_SIGNAL(selectionChanged(TQListViewItem*)),
          this, TQT_SLOT(selectionChanged(TQListViewItem*)));
  connect(m_documentList, TQT_SIGNAL(clicked(TQListViewItem*)),
          this, TQT_SLOT(selectionChanged(TQListViewItem*)));
  connect(m_documentList, TQT_SIGNAL(doubleClicked(TQListViewItem*, const TQPoint&, int)),
          this, TQT_SLOT(openFile(TQListViewItem*)));
  connect(m_documentList, TQT_SIGNAL(returnPressed(TQListViewItem*)),
          this, TQT_SLOT(openFile(TQListViewItem*)));
  connect(m_openButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(openFile()));

  m_documentList->setSelected(m_documentList->firstChild(), true);

  d->m_previewJob = TDEIO::filePreview(fileList, 200, 200);

  connect(d->m_previewJob, TQT_SIGNAL(result(TDEIO::Job*)), this, TQT_SLOT(previewResult(TDEIO::Job*)));
  connect(d->m_previewJob, TQT_SIGNAL(gotPreview(const KFileItem*, const TQPixmap&)),
          this, TQT_SLOT(updatePreview(const KFileItem*, const TQPixmap&)));
}

KoRecentDocumentsPane::~KoRecentDocumentsPane()
{
  delete d;
}

void KoRecentDocumentsPane::selectionChanged(TQListViewItem* item)
{
  if(item) {
    m_openButton->setEnabled(true);
    m_titleLabel->setText(item->text(0));
    m_previewLabel->setPixmap(*(item->pixmap(2)));

    if(static_cast<KoFileListItem*>(item)->fileItem()) {
      KFileItem* fileItem = static_cast<KoFileListItem*>(item)->fileItem();
      TQString details = "<center><table border=\"0\">";
      details += i18n("File modification date and time. %1 is date time", "<tr><td><b>Modified:</b></td><td>%1</td></tr>")
          .arg(fileItem->timeString(TDEIO::UDS_MODIFICATION_TIME));
      details += i18n("File access date and time. %1 is date time", "<tr><td><b>Accessed:</b></td><td>%1</td></tr>")
          .arg(fileItem->timeString(TDEIO::UDS_ACCESS_TIME));
      details += "</table></center>";
      m_detailsLabel->setText(details);
    } else {
      m_detailsLabel->setText(TQString());
    }
  } else {
    m_openButton->setEnabled(false);
    m_titleLabel->setText(TQString());
    m_previewLabel->setPixmap(TQPixmap());
    m_detailsLabel->setText(TQString());
  }
}

void KoRecentDocumentsPane::openFile()
{
  TQListViewItem* item = m_documentList->selectedItem();
  openFile(item);
}

void KoRecentDocumentsPane::openFile(TQListViewItem* item)
{
  TDEConfigGroup cfgGrp(d->m_instance->config(), "TemplateChooserDialog");
  cfgGrp.writeEntry("LastReturnType", "File");

  if(item)
    emit openFile(item->text(1));
}

void KoRecentDocumentsPane::previewResult(TDEIO::Job* job)
{
  if(d->m_previewJob == job)
    d->m_previewJob = 0;
}

void KoRecentDocumentsPane::updatePreview(const KFileItem* fileItem, const TQPixmap& preview)
{
  if(preview.isNull()) {
    return;
  }

  TQListViewItemIterator it(m_documentList);

  while(it.current()) {
    if(it.current()->text(1) == fileItem->url().url()) {
      it.current()->setPixmap(2, preview);
      TQImage icon = preview.convertToImage();
      icon = icon.smoothScale(64, 64, TQ_ScaleMin);
      icon.setAlphaBuffer(true);
      icon = icon.copy((icon.width() - 64) / 2, (icon.height() - 64) / 2, 64, 64);
      it.current()->setPixmap(0, TQPixmap(icon));

      if(it.current()->isSelected()) {
        m_previewLabel->setPixmap(preview);
      }

      break;
    }

    it++;
  }
}

void KoRecentDocumentsPane::changePalette()
{
  TQPalette p = kapp ? kapp->palette() : palette();
  p.setBrush(TQColorGroup::Base, p.brush(TQPalette::Normal, TQColorGroup::Background));
  p.setColor(TQColorGroup::Text, p.color(TQPalette::Normal, TQColorGroup::Foreground));
  m_detailsLabel->setPalette(p);
}

bool KoRecentDocumentsPane::eventFilter(TQObject* watched, TQEvent* e)
{
  if(TQT_BASE_OBJECT(watched) == m_previewLabel) {
    if(e->type() == TQEvent::MouseButtonDblClick) {
      openFile();
    }
  }

  if(TQT_BASE_OBJECT(watched) == m_documentList) {
    if((e->type() == TQEvent::Resize) && isShown()) {
      emit splitterResized(this, m_splitter->sizes());
    }
  }

  return false;
}

void KoRecentDocumentsPane::resizeSplitter(KoDetailsPaneBase* sender, const TQValueList<int>& sizes)
{
  if(sender == this)
    return;

  m_splitter->setSizes(sizes);
}

#include "KoDetailsPane.moc"