/***************************************************************************
                          kexportdlg.cpp  -  description
                             -------------------
    begin                : Tue May 22 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>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 <tqlabel.h>
#include <tqpixmap.h>

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

#include <tdeglobal.h>
#include <tdelocale.h>
#include <tdestandarddirs.h>
#include <tdemessagebox.h>
#include <tdefiledialog.h>
#include <kpushbutton.h>
#include <kiconloader.h>

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

#include "kexportdlg.h"
#include "../mymoney/mymoneycategory.h"
#include "../dialogs/mymoneyqifprofileeditor.h"
#include "../mymoney/mymoneyfile.h"
#include "../widgets/kmymoneyaccountcombo.h"
#include "../kmymoneyutils.h"

KExportDlg::KExportDlg(TQWidget *parent)
  : KExportDlgDecl(parent, 0, true)
{
  // Set (almost) all the last used options
  readConfig();

  loadProfiles(true);
  loadAccounts();

  // load button icons
  TDEIconLoader* il = TDEGlobal::iconLoader();
  m_qbuttonCancel->setGuiItem(KStdGuiItem::cancel());

  KGuiItem okButtenItem( i18n( "&Export" ),
                      TQIconSet(il->loadIcon("fileexport", TDEIcon::Small, TDEIcon::SizeSmall)),
                      i18n("Start operation"),
                      i18n("Use this to start the export 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_profileEditorButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotNewProfile()));
  connect(m_qbuttonOk, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotOkClicked()));
  connect(m_qbuttonCancel, TQ_SIGNAL(clicked()), this, TQ_SLOT(reject()));

  // connect the change signals to the check slot and perform initial check
  connect(m_qlineeditFile, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(checkData()));
  connect(m_qcheckboxAccount, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(checkData()));
  connect(m_qcheckboxCategories, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(checkData()));
  connect(m_accountComboBox, TQ_SIGNAL(accountSelected(const TQString&)), this, TQ_SLOT(checkData(const TQString&)));
  connect(m_profileComboBox, TQ_SIGNAL(highlighted(int)), this, TQ_SLOT(checkData()));
  connect(m_kmymoneydateStart, TQ_SIGNAL(dateChanged(const TQDate&)), this, TQ_SLOT(checkData()));
  connect(m_kmymoneydateEnd, TQ_SIGNAL(dateChanged(const TQDate&)), this, TQ_SLOT(checkData()));

  checkData(TQString());
}

KExportDlg::~KExportDlg()
{
}

void KExportDlg::slotBrowse()
{
  TQString newName(KFileDialog::getSaveFileName(TQString(),"*.QIF"));
  KMyMoneyUtils::appendCorrectFileExt(newName, TQString("qif"));
  if (!newName.isEmpty())
    m_qlineeditFile->setText(newName);
}

void KExportDlg::slotNewProfile(void)
{
  MyMoneyQifProfileEditor* editor = new MyMoneyQifProfileEditor(true, this, "QIF Profile Editor");
  if(editor->exec()) {
    m_profileComboBox->setCurrentText(editor->selectedProfile());
    loadProfiles();
  }
  delete editor;
}

void KExportDlg::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("KExportDlg_LastProfile");
  }

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

void KExportDlg::slotOkClicked()
{
  // Make sure we save the last used settings for use next time,
  writeConfig();
  accept();
}

void KExportDlg::readConfig(void)
{
  TDEConfig *tdeconfig = TDEGlobal::config();
  tdeconfig->setGroup("Last Use Settings");
  m_qlineeditFile->setText(tdeconfig->readEntry("KExportDlg_LastFile"));
  m_qcheckboxAccount->setChecked(tdeconfig->readBoolEntry("KExportDlg_AccountOpt", true));
  m_qcheckboxCategories->setChecked(tdeconfig->readBoolEntry("KExportDlg_CatOpt", true));
  m_kmymoneydateStart->setDate(tdeconfig->readDateTimeEntry("KExportDlg_StartDate").date());
  m_kmymoneydateEnd->setDate(tdeconfig->readDateTimeEntry("KExportDlg_EndDate").date());
  // m_profileComboBox is loaded in loadProfiles(), so we don't worry here
  // m_accountComboBox is loaded in loadAccounts(), so we don't worry here
}

void KExportDlg::writeConfig(void)
{
  TDEConfig *tdeconfig = TDEGlobal::config();
  tdeconfig->setGroup("Last Use Settings");
  tdeconfig->writeEntry("KExportDlg_LastFile", m_qlineeditFile->text());
  tdeconfig->writeEntry("KExportDlg_AccountOpt", m_qcheckboxAccount->isChecked());
  tdeconfig->writeEntry("KExportDlg_CatOpt", m_qcheckboxCategories->isChecked());
  tdeconfig->writeEntry("KExportDlg_StartDate", TQDateTime(m_kmymoneydateStart->date()));
  tdeconfig->writeEntry("KExportDlg_EndDate", TQDateTime(m_kmymoneydateEnd->date()));
  tdeconfig->writeEntry("KExportDlg_LastProfile", m_profileComboBox->currentText());
  tdeconfig->sync();
}

void KExportDlg::checkData(const TQString& accountId)
{
  bool  okEnabled = false;

  if(!m_qlineeditFile->text().isEmpty()) {
    TQString strFile(m_qlineeditFile->text());
    if(KMyMoneyUtils::appendCorrectFileExt(strFile, TQString("qif")))
      m_qlineeditFile->setText(strFile);
  }

  MyMoneyAccount account;
  if(!accountId.isEmpty()) {
    MyMoneyFile* file = MyMoneyFile::instance();
    account = file->account(accountId);
    if(m_lastAccount != accountId) {
      MyMoneyTransactionFilter filter(accountId);
      TQValueList<MyMoneyTransaction> list = file->transactionList(filter);
      TQValueList<MyMoneyTransaction>::Iterator it;

      if(!list.isEmpty()) {
        it = list.begin();
        m_kmymoneydateStart->loadDate((*it).postDate());
        it = list.end();
        --it;
        m_kmymoneydateEnd->loadDate((*it).postDate());
      }
      m_lastAccount = accountId;
      m_accountComboBox->setSelected(account);
    }
  }

  if(!m_qlineeditFile->text().isEmpty()
  && m_accountComboBox->selectedAccounts().count() != 0
  && !m_profileComboBox->currentText().isEmpty()
  && m_kmymoneydateStart->date() <= m_kmymoneydateEnd->date()
  && (m_qcheckboxAccount->isChecked() || m_qcheckboxCategories->isChecked()))
    okEnabled = true;

  m_qbuttonOk->setEnabled(okEnabled);
}

void KExportDlg::loadAccounts(void)
{
/*
  TQStringList strList;

  try {
    MyMoneyFile *file = MyMoneyFile::instance();

    // read all account items from the MyMoneyFile objects and add them to the listbox
    addCategories(strList, file->liability().id(), TQString());
    addCategories(strList, file->asset().id(), TQString());

  } catch (MyMoneyException *e) {
    tqDebug("Exception '%s' thrown in %s, line %ld caught in KExportDlg::loadAccounts:%d",
      e->what().latin1(), e->file().latin1(), e->line(), __LINE__);
    delete e;
  }
*/
  m_accountComboBox->loadList((KMyMoneyUtils::categoryTypeE)(KMyMoneyUtils::asset | KMyMoneyUtils::liability));

/*
  m_accountComboBox->setCurrentItem(0);
  if(strList.contains(current) > 0)
    m_accountComboBox->setCurrentText(current);
*/
}

TQString KExportDlg::accountId() const
{
  return m_lastAccount;
}

/*
void KExportDlg::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() + ":");
  }
}

TQString KExportDlg::accountId(const TQString& account) const
{
  return MyMoneyFile::instance()->nameToAccount(account);
}
*/

#include "kexportdlg.moc"
