/***************************************************************************
                          KStartDlg.cpp  -  description
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

// ----------------------------------------------------------------------------
// QT Includes

#include <tqvbox.h>
#include <tqlayout.h>
#include <tqbuttongroup.h>
#include <tqabstractlayout.h>
#include <tqpixmap.h>
#include <tqtextview.h>
#include <tqlabel.h>

// ----------------------------------------------------------------------------
// KDE Includes

#include "kdecompat.h"

#include <kstandarddirs.h>

#include <kiconloader.h>
#include <tdeconfig.h>
#include <tdeglobalsettings.h>
#include <tdefiledialog.h>
#include <kurl.h>
#include <kurlrequester.h>
#include <tdefile.h>
#include <tdeio/netaccess.h>
#include <tdemessagebox.h>

// ----------------------------------------------------------------------------
// Project Includes

#include "kstartdlg.h"
#include "tderecentfileitem.h"
#include "../kmymoney2.h"

#include <tqtooltip.h>

KStartDlg::KStartDlg(TQWidget *parent, const char *name, bool modal) : KDialogBase(IconList,i18n("Start Dialog"),Help|Ok|Cancel,Ok, parent, name, modal, true)
{
  setPage_Template();
  setPage_Documents();

  isnewfile = false;
  isopenfile = false;

  readConfig();
}

KStartDlg::~KStartDlg()
{
}

/** Set the font  Page of the preferences dialog */
void KStartDlg::setPage_Template()
{
  TDEIconLoader *ic = TDEGlobal::iconLoader();
  templateMainFrame = addVBoxPage( i18n("Templates"), i18n("Select templates"), DesktopIcon("wizard"));
  view_wizard = new TDEIconView( templateMainFrame, "view_options" );
  (void)new TQIconViewItem( view_wizard, i18n("New KMyMoney document"), ic->loadIcon("mime_empty.png", TDEIcon::Desktop, TDEIcon::SizeLarge)/*TQPixmap( locate("icon","hicolor/48x48/mimetypes/mime_empty.png") )*/ );
  connect(view_wizard, TQT_SIGNAL(executed(TQIconViewItem *) ), this, TQT_SLOT(slotTemplateClicked(TQIconViewItem *) ) );
  connect(view_wizard, TQT_SIGNAL(selectionChanged(TQIconViewItem*)),
    this, TQT_SLOT(slotTemplateSelectionChanged(TQIconViewItem*)));
  connect(this, TQT_SIGNAL(aboutToShowPage(TQWidget*)), this, TQT_SLOT(slotAboutToShowPage(TQWidget*)));
}

/** Set the Misc options Page of the preferences dialog */
void KStartDlg::setPage_Documents()
{
  recentMainFrame = addPage( i18n("Open"), i18n("Open a KMyMoney document"), DesktopIcon("document-open"));
  TQVBoxLayout *mainLayout = new TQVBoxLayout( recentMainFrame );

  kurlrequest = new KURLRequester( recentMainFrame, "kurlrequest" );

  //allow user to select either a .kmy file, or any generic file.
  kurlrequest->fileDialog()->setFilter( i18n("%1|KMyMoney files (*.kmy)\n" "%2|All files (*.*)").arg("*.kmy").arg("*.*") );
  kurlrequest->fileDialog()->setMode(KFile::File || KFile::ExistingOnly);
  kurlrequest->fileDialog()->setURL(KURL(kmymoney2->readLastUsedDir()));//kurlrequest->fileDialog()->setURL(KURL(TDEGlobalSettings::documentPath()));
  mainLayout->addWidget( kurlrequest );

  TQLabel *label1 = new TQLabel( recentMainFrame, "label1" );
  label1->setText( i18n("Recent Files") );
  mainLayout->addWidget( label1 );
  view_recent = new TDEIconView( recentMainFrame, "view_recent" );
  connect( view_recent, TQT_SIGNAL( executed(TQIconViewItem *) ), this, TQT_SLOT( slotRecentClicked(TQIconViewItem *) ) );
  mainLayout->addWidget( view_recent );
  view_recent->setArrangement(TDEIconView::LeftToRight/*TopToBottom*/);
  view_recent->setItemTextPos(TDEIconView::Bottom);

  connect(view_recent, TQT_SIGNAL(selectionChanged(TQIconViewItem*)),
    this, TQT_SLOT(slotRecentSelectionChanged(TQIconViewItem*)));
}

void KStartDlg::slotTemplateClicked(TQIconViewItem *item)
{
  if(!item) return;

  // If the item is the blank document turn isnewfile variable true, else is template or wizard
  if( item->text() == i18n("New KMyMoney document") )
     isnewfile = true;
   else
     templatename = item->text();

  isopenfile = false;
  // Close the window if the user pressed an icon
  slotOk();
}

/** Read config window */
void KStartDlg::readConfig()
{
  TQString value;
  unsigned int i = 1;

  TDEConfig *config = TDEGlobal::config();
  TDEIconLoader *il = TDEGlobal::iconLoader();

  // read file list
  do {
    // for some reason, I had to setup the group to get reasonable results
    // after program startup. If the wizard was opened the second time,
    // it does not make a difference, if you call setGroup() outside of
    // this loop. The first time it does make a difference!
    config->setGroup("Recent Files");
    value = config->readEntry( TQString( "File%1" ).arg( i ), TQString() );
    if( !value.isNull() && fileExists(value) )
    {
      TQString file_name = value.mid(value.findRev('/')+1);
      (void)new TDERecentFileItem( value, view_recent, file_name, il->loadIcon("kmy", TDEIcon::Desktop, TDEIcon::SizeLarge));
    }
    i++;
  } while( !value.isNull() );

  config->setGroup("Start Dialog");
  TQSize *defaultSize = new TQSize(400,300);
  this->resize( config->readSizeEntry("Geometry", defaultSize ) );

  // Restore the last page viewed
  // default to the recent files page if no entry exists but files have been found
  // otherwise, default to template page
  if(view_recent->count() > 0)
    showPage(config->readNumEntry("LastPage", this->pageIndex(recentMainFrame)));
  else {
    showPage(config->readNumEntry("LastPage", this->pageIndex(templateMainFrame)));
    slotAboutToShowPage(templateMainFrame);
  }
}

/** Write config window */
void KStartDlg::writeConfig()
{
  TDEConfig *config = TDEGlobal::config();

  config->setGroup("Start Dialog");
  config->writeEntry("Geometry", this->size() );
  config->writeEntry("LastPage", this->activePageIndex());
  config->sync();
}

/** slot to recent view */
void KStartDlg::slotRecentClicked(TQIconViewItem *item)
{
  TDERecentFileItem *kitem = (TDERecentFileItem*)item;
  if(!kitem) return;

  isopenfile = true;
  kurlrequest->setURL( kitem->fileURL() );
  // Close the window if the user press an icon
  slotOk();
}

/** No descriptions */
void KStartDlg::slotOk()
{
  writeConfig();
  this->accept();
}

bool KStartDlg::fileExists(KURL url)
{
#if KDE_IS_VERSION(3,2,0)
  return TDEIO::NetAccess::exists(url, true, this);
#else
  return TDEIO::NetAccess::exists(url);
#endif
}

void KStartDlg::slotTemplateSelectionChanged(TQIconViewItem* item)
{
  if(!item) return;

  // Clear the other selection
  view_recent->clearSelection();

  // If the item is the blank document turn isnewfile
  // variable true, else is template or wizard
  if( item->text() == i18n("Blank Document") )
    isnewfile = true;
  else
    templatename = item->text();

  isopenfile = false;
}

void KStartDlg::slotRecentSelectionChanged(TQIconViewItem* item)
{
  TDERecentFileItem *kitem = (TDERecentFileItem*)item;
  if(!kitem) return;

  // Clear the other selection
  view_wizard->clearSelection();

  isnewfile = false;
  isopenfile = true;
  kurlrequest->setURL( kitem->fileURL() );
}

void KStartDlg::slotAboutToShowPage(TQWidget* page)
{
  enableButtonOK(page == recentMainFrame);
}

#include "kstartdlg.moc"
