/***************************************************************************
                          kimportdlg.cpp  -  description
                             -------------------
    begin                : Wed May 16 2001
    copyright            : (C) 2001 by Michael Edwardes
    email                : mte@users.sourceforge.net
                           Javier Campos Morales <javi_c@ctv.es>
                           Felix Rodriguez <frodriguez@mail.wesleyan.edu>
                           Thomas Baumgart <ipwizard@users.sourceforge.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.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// ----------------------------------------------------------------------------
// TQt Headers

#include <tqlineedit.h>
#include <tqtextstream.h>
#include <tqprogressbar.h>
#include <tqlabel.h>
#include <tqbuttongroup.h>
#include <tqpixmap.h>
#include <tqapplication.h>

// ----------------------------------------------------------------------------
// TDE Headers

#include <tdeglobalsettings.h>
#include <kpushbutton.h>
#include <kcombobox.h>
#include <tdemessagebox.h>
#include <tdefiledialog.h>
#include <tdelocale.h>
#include <tdeglobal.h>
#include <kiconloader.h>
#include <tdeio/netaccess.h>
#include <tdestandarddirs.h>

// ----------------------------------------------------------------------------
// Project Headers

#include "kimportdlg.h"
#include <kmymoney/mymoneyfile.h>
#include "mymoneyqifprofileeditor.h"
#include "../converter/mymoneyqifprofile.h"

KImportDlg::KImportDlg(TQWidget *parent, const char * name)
  : KImportDlgDecl(parent, name, true)
{
  // Set all the last used options
  readConfig();

  loadProfiles(true);

  // load button icons
  m_qbuttonCancel->setGuiItem(KStdGuiItem::cancel());

  TDEIconLoader* il = TDEGlobal::iconLoader();
  KGuiItem okButtenItem( i18n( "&Import" ),
                      TQIconSet(il->loadIcon("fileimport", TDEIcon::Small, TDEIcon::SizeSmall)),
                      i18n("Start operation"),
                      i18n("Use this to start the import operation"));
  m_qbuttonOk->setGuiItem(okButtenItem);

  KGuiItem browseButtenItem( i18n( "&Browse..." ),
                      TQIconSet(il->loadIcon("document-open", TDEIcon::Small, TDEIcon::SizeSmall)),
                      i18n("Select filename"),
                      i18n("Use this to select a filename to export to"));
  m_qbuttonBrowse->setGuiItem(browseButtenItem);

  KGuiItem newButtenItem( i18n( "&New..." ),
                      TQIconSet(il->loadIcon("document-new", TDEIcon::Small, TDEIcon::SizeSmall)),
                      i18n("Create a new profile"),
                      i18n("Use this to open the profile editor"));
  m_profileEditorButton->setGuiItem(newButtenItem);

  // connect the buttons to their functionality
  connect(m_qbuttonBrowse, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotBrowse() ) );
  connect(m_qbuttonOk, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotOkClicked()));
  connect(m_qbuttonCancel, TQ_SIGNAL(clicked()), this, TQ_SLOT(reject()));
  connect(m_profileEditorButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotNewProfile()));

  // connect the change signals to the check slot and perform initial check
  connect(m_qlineeditFile, TQ_SIGNAL(textChanged(const TQString&)), this,
    TQ_SLOT(slotFileTextChanged(const TQString&)));

  // setup button enable status
  slotFileTextChanged(m_qlineeditFile->text());
}

KImportDlg::~KImportDlg()
{
}

void KImportDlg::slotBrowse()
{
  // determine what the browse prefix should be from the current profile

  MyMoneyQifProfile tmpprofile;
  tmpprofile.loadProfile("Profile-" + profile());

  KFileDialog dialog(TDEGlobalSettings::documentPath(),
                     i18n("%1|Import files\n%2|All files (*.*)").arg(tmpprofile.filterFileType()).arg("*"),
                     this, i18n("Import File...").utf8(), true);
  dialog.setMode(KFile::File | KFile::ExistingOnly);

  if(dialog.exec() == TQDialog::Accepted) {
    m_qlineeditFile->setText(dialog.selectedURL().pathOrURL());
  }
}

void KImportDlg::slotOkClicked()
{
  // Save the used options.
  writeConfig();
  // leave dialog directly
  accept();
}

void KImportDlg::readConfig(void)
{
  TDEConfig *tdeconfig = TDEGlobal::config();
  tdeconfig->setGroup("Last Use Settings");
  m_qlineeditFile->setText(tdeconfig->readEntry("KImportDlg_LastFile"));
}

void KImportDlg::writeConfig(void)
{
  TDEConfig *tdeconfig = TDEGlobal::config();
  tdeconfig->setGroup("Last Use Settings");
  tdeconfig->writeEntry("KImportDlg_LastFile", m_qlineeditFile->text());
  tdeconfig->writeEntry("KImportDlg_LastProfile", m_profileComboBox->currentText());
  tdeconfig->sync();
}

/** Make sure the text input is ok */
void KImportDlg::slotFileTextChanged(const TQString& text)
{
  if (!text.isEmpty() && TDEIO::NetAccess::exists(text, true, tqApp->mainWidget())) {
    // m_qcomboboxDateFormat->setEnabled(true);
    m_qbuttonOk->setEnabled(true);
    m_qlineeditFile->setText(text);
  } else {
    // m_qcomboboxDateFormat->setEnabled(false);
    m_qbuttonOk->setEnabled(false);
  }
}

void KImportDlg::slotNewProfile(void)
{
  MyMoneyQifProfileEditor* editor = new MyMoneyQifProfileEditor(true, this, "QIF Profile Editor");

  if(editor->exec()) {
    m_profileComboBox->setCurrentText(editor->selectedProfile());
    loadProfiles();
  }

  delete editor;
}

void KImportDlg::slotSelectProfile(const TQString& profile)
{
  m_profileComboBox->setCurrentText(profile);
  loadProfiles();
}

void KImportDlg::loadProfiles(const bool selectLast)
{
  // Creating an editor object here makes sure that
  // we have at least the default profile available
  MyMoneyQifProfileEditor* edit = new MyMoneyQifProfileEditor(true, 0, 0);
  edit->slotOk();
  delete edit;

  TQString current = m_profileComboBox->currentText();

  m_profileComboBox->clear();

  TQStringList list;
  TDEConfig* config = TDEGlobal::config();
  config->setGroup("Profiles");

  list = config->readListEntry("profiles");
  list.sort();
  m_profileComboBox->insertStringList(list);

  if(selectLast == true) {
    config->setGroup("Last Use Settings");
    current = config->readEntry("KImportDlg_LastProfile");
  }

  m_profileComboBox->setCurrentItem(0);
  if(list.contains(current) > 0) {
    m_profileComboBox->setCurrentText(current);
  }
}

void KImportDlg::addCategories(TQStringList& strList, const TQString& id, const TQString& leadIn) const
{
  MyMoneyFile *file = MyMoneyFile::instance();
  TQString name;

  MyMoneyAccount account = file->account(id);

  TQStringList accList = account.accountList();
  TQStringList::ConstIterator it_a;

  for(it_a = accList.begin(); it_a != accList.end(); ++it_a) {
    account = file->account(*it_a);
    strList << leadIn + account.name();
    addCategories(strList, *it_a, leadIn + account.name() + MyMoneyFile::AccountSeperator);
  }
}


#include "kimportdlg.moc"
