/***************************************************************************
                          ksecuritylisteditor.cpp  -  description
                             -------------------
    begin                : Wed Dec 16 2004
    copyright            : (C) 2004 by Thomas Baumgart
    email                : 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 Includes

#include <tqcheckbox.h>

// ----------------------------------------------------------------------------
// TDE Includes

#include <kpushbutton.h>
#include <tdelistview.h>
#include <kguiitem.h>
#include <kiconloader.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <tdemessagebox.h>

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

#include "ksecuritylisteditor.h"

#include "../mymoney/mymoneysecurity.h"
#include "../mymoney/mymoneyfile.h"
#include "../dialogs/knewinvestmentwizard.h"

#include "../kmymoneyutils.h"

#define ID_COL        0
#define TYPE_COL      1
#define NAME_COL      2
#define SYMBOL_COL    3
#define MARKET_COL    4
#define CURR_COL      5
#define ACCFRACT_COL  6
#define CASHFRACT_COL 7

#define CURRENCY_MARKET    TQString("ISO 4217")

KSecurityListEditor::KSecurityListEditor(TQWidget *parent, const char *name) :
  KSecurityListEditorDecl(parent, name)
{
  m_listView->setColumnWidth(ID_COL, 0);
  m_listView->setColumnWidthMode(NAME_COL, TQListView::Maximum);
  m_listView->setColumnWidthMode(ID_COL, TQListView::Manual);
  m_listView->setColumnAlignment(CURR_COL, TQt::AlignHCenter);
  m_listView->setMultiSelection(false);
  m_listView->setAllColumnsShowFocus(true);

  TDEIconLoader *il = TDEGlobal::iconLoader();
  KGuiItem removeButtenItem( i18n( "&Delete" ),
                    TQIconSet(il->loadIcon("delete", TDEIcon::Small, TDEIcon::SizeSmall)),
                    i18n("Delete this entry"),
                    i18n("Remove this security item from the file"));
  m_deleteButton->setGuiItem(removeButtenItem);

  KGuiItem addButtenItem( i18n( "&Add" ),
                    TQIconSet(il->loadIcon("file_new", TDEIcon::Small, TDEIcon::SizeSmall)),
                    i18n("Add a new entry"),
                    i18n("Create a new security entry."));
  m_addButton->setGuiItem(addButtenItem);

  KGuiItem editButtenItem( i18n( "&Edit" ),
                    TQIconSet(il->loadIcon("edit", TDEIcon::Small, TDEIcon::SizeSmall)),
                    i18n("Modify the selected entry"),
                    i18n("Change the security information of the selected entry."));
  m_editButton->setGuiItem(editButtenItem);

  KGuiItem okButtenItem( i18n("&Close" ),
                    TQIconSet(il->loadIcon("button_ok", TDEIcon::Small, TDEIcon::SizeSmall)),
                    i18n("Close the dialog"),
                    i18n("Use this to close the dialog and return to the application."));
  m_closeButton->setGuiItem(okButtenItem);

  connect(m_closeButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(reject()));
  connect(m_showCurrencyButton, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotLoadList()));
  connect(m_listView, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(slotUpdateButtons()));

  connect(m_editButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotEditSecurity()));
  connect(m_deleteButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotDeleteSecurity()));

  // FIXME for now, the only way to add a new security is to add a new investment
  m_addButton->hide();

  slotLoadList();
}

KSecurityListEditor::~KSecurityListEditor()
{
}

void KSecurityListEditor::slotLoadList(void)
{
  m_listView->clear();

  TQValueList<MyMoneySecurity> list = MyMoneyFile::instance()->securityList();
  TQValueList<MyMoneySecurity>::ConstIterator it;
  if(m_showCurrencyButton->isChecked()) {
    list += MyMoneyFile::instance()->currencyList();
  }
  for(it = list.begin(); it != list.end(); ++it) {
    TDEListViewItem* newItem = new TDEListViewItem(m_listView, TQString((*it).id()));
    fillItem(newItem, *it);

  }
  slotUpdateButtons();
}

void KSecurityListEditor::fillItem(TQListViewItem* item, const MyMoneySecurity& security)
{
  TQString market = security.tradingMarket();
  MyMoneySecurity tradingCurrency;
  if(security.isCurrency())
    market = CURRENCY_MARKET;
  else
    tradingCurrency = MyMoneyFile::instance()->security(security.tradingCurrency());

  item->setText(TYPE_COL, KMyMoneyUtils::securityTypeToString(security.securityType()));
  item->setText(NAME_COL, security.name());
  item->setText(SYMBOL_COL, security.tradingSymbol());
  item->setText(MARKET_COL, market);
  item->setText(CURR_COL, tradingCurrency.tradingSymbol());
  item->setText(ACCFRACT_COL, TQString::number(security.smallestAccountFraction()));

  // smallestCashFraction is only applicable for currencies
  if(security.isCurrency())
    item->setText(CASHFRACT_COL, TQString::number(security.smallestCashFraction()));
}

void KSecurityListEditor::slotUpdateButtons(void)
{
  TQListViewItem* item = m_listView->selectedItem();

  if(item) {
    MyMoneySecurity security = MyMoneyFile::instance()->security(item->text(ID_COL).latin1());
    m_editButton->setEnabled(item->text(MARKET_COL) != CURRENCY_MARKET);
    m_deleteButton->setEnabled(!MyMoneyFile::instance()->isReferenced(security));

  } else {
    m_editButton->setEnabled(false);
    m_deleteButton->setEnabled(false);
  }
}

void KSecurityListEditor::slotEditSecurity(void)
{
  TQListViewItem* item = m_listView->selectedItem();
  if(item) {
    MyMoneySecurity security = MyMoneyFile::instance()->security(item->text(ID_COL).latin1());

    KNewInvestmentWizard dlg(security, this, "KNewInvestmentWizard");
    if(dlg.exec() == TQDialog::Accepted) {
      dlg.createObjects(TQString());
      security = MyMoneyFile::instance()->security(item->text(ID_COL).latin1());
      fillItem(item, security);
    }
  }
}

void KSecurityListEditor::slotDeleteSecurity(void)
{
  TQListViewItem* item = m_listView->selectedItem();
  if(item) {
    MyMoneySecurity security = MyMoneyFile::instance()->security(item->text(ID_COL).latin1());
    TQString msg;
    TQString dontAsk;
    if(security.isCurrency()) {
      msg = TQString("<p>") + i18n("Do you really want to remove the currency <b>%1</b> from the file?</p><i>Note: It is currently not supported to add currencies.</i>").arg(security.name());
      dontAsk = "DeleteCurrency";
    } else {
      msg = TQString("<p>") + i18n("Do you really want to remove the %1 <b>%2</b> from the file?").arg(KMyMoneyUtils::securityTypeToString(security.securityType())).arg(security.name());
      dontAsk = "DeleteSecurity";
    }
    if(KMessageBox::questionYesNo(this, msg, i18n("Delete security"), KStdGuiItem::yes(), KStdGuiItem::no(), dontAsk) == KMessageBox::Yes) {
      MyMoneyFileTransaction ft;
      try {
        if(security.isCurrency())
          MyMoneyFile::instance()->removeCurrency(security);
        else
          MyMoneyFile::instance()->removeSecurity(security);
        ft.commit();
        slotLoadList();
      } catch(MyMoneyException *e) {
        delete e;
      }
    }
  }
}

// Make sure, that these definitions are only used within this file
// this does not seem to be necessary, but when building RPMs the
// build option 'final' is used and all CPP files are concatenated.
// So it could well be, that in another CPP file these definitions
// are also used.
#undef ID_COL
#undef TYPE_COL
#undef NAME_COL
#undef SYMBOL_COL
#undef MARKET_COL
#undef CURR_COL
#undef ACCFRACT_COL
#undef CASHFRACT_COL

#include "ksecuritylisteditor.moc"
