/***************************************************************************
                          kcurrencyeditdlg.cpp  -  description
                             -------------------
    begin                : Wed Mar 24 2004
    copyright            : (C) 2000-2004 by Michael Edwardes
    email                : mte@users.sourceforge.net
                           Javier Campos Morales <javi_c@users.sourceforge.net>
                           Felix Rodriguez <frodriguez@users.sourceforge.net>
                           John C <thetacoturtle@users.sourceforge.net>
                           Thomas Baumgart <ipwizard@users.sourceforge.net>
                           Kevin Tambascio <ktambascio@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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <locale.h>

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

#include <tqheader.h>
#include <tqtimer.h>

#include <tqpixmap.h>
#include <tqbitmap.h>
#include <tqlabel.h>
#include <tqgroupbox.h>

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

#include <tdelocale.h>
#include <kpushbutton.h>
#include <tdelistview.h>
#include <kstandarddirs.h>
#include <tdemessagebox.h>
#include <kinputdialog.h>

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

#include "kcurrencyeditdlg.h"

#include <kmymoney/mymoneysecurity.h>
#include <kmymoney/mymoneyfile.h>
#include <kmymoney/kmymoneylistviewitem.h>
#include <kmymoney/kmymoneyaccountselector.h>
#include <kmymoney/kmymoneylineedit.h>

#include "../widgets/kmymoneypriceview.h"

KCurrencyEditDlg::KCurrencyEditDlg(TQWidget *parent, const char *name ) :
  KCurrencyEditDlgDecl(parent,name)
{
  m_currencyList->addColumn(i18n("Currency"));
  m_currencyList->header()->hide();

  // FIXME: the online source table currently has no functionality
  m_onlineSourceTable->hide();

  connect(m_currencyList, TQT_SIGNAL(rightButtonPressed(TQListViewItem* , const TQPoint&, int)),
          this, TQT_SLOT(slotListClicked(TQListViewItem*, const TQPoint&, int)));
  connect(m_currencyList, TQT_SIGNAL(selectionChanged(TQListViewItem*)), this, TQT_SLOT(slotSelectCurrency(TQListViewItem*)));


  connect(m_currencyList, TQT_SIGNAL(itemRenamed(TQListViewItem*,int,const TQString&)), this, TQT_SIGNAL(renameCurrency(TQListViewItem*,int,const TQString&)));
  connect(MyMoneyFile::instance(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotLoadCurrencies()));

  slotLoadCurrencies();

  connect(m_baseCurrencyButton, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotSelectBaseCurrency()));
  connect(buttonClose, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotClose()));

  // FIXME: currently, no online help available
  buttonHelp->hide();

  // FIXME this is currently unused so we hide it also
  m_description->hide();

  resize(width()-1, height()-1);
  TQTimer::singleShot(10, this, TQT_SLOT(timerDone()));
}

void KCurrencyEditDlg::timerDone(void)
{
  if(!m_currency.id().isEmpty()) {
    TQListViewItemIterator it(m_currencyList);
    TQListViewItem* q;
    while((q = it.current()) != 0) {
      KMyMoneyListViewItem* p = static_cast<KMyMoneyListViewItem *>(q);
      if(p->id() == m_currency.id()) {
        m_currencyList->ensureItemVisible(q);
        break;
      }
      ++it;
    }
  }
  // the resize operation does the trick to adjust
  // all widgets in the view to the size they should
  // have and show up correctly. Don't ask me, why
  // this is, but it cured the problem (ipwizard).
  resize(width()+1, height()+1);
}

KCurrencyEditDlg::~KCurrencyEditDlg()
{
}

void KCurrencyEditDlg::resizeEvent(TQResizeEvent* /* e*/)
{
  int w = m_currencyList->visibleWidth();

  m_currencyList->setColumnWidth(0, w);
}

void KCurrencyEditDlg::slotLoadCurrencies(void)
{
  TQValueList<MyMoneySecurity> list = MyMoneyFile::instance()->currencyList();
  TQValueList<MyMoneySecurity>::ConstIterator it;
  TQListViewItem *first = 0;

  TQString localCurrency(localeconv()->int_curr_symbol);
  localCurrency.truncate(3);

  TQString baseCurrency = MyMoneyFile::instance()->baseCurrency().id();
  // construct a transparent 16x16 pixmap
  TQPixmap empty(16, 16);
  empty.setMask(TQBitmap(16, 16, true));

  m_currencyList->clear();
  for(it = list.begin(); it != list.end(); ++it) {
    KMyMoneyListViewItem* p = new KMyMoneyListViewItem(m_currencyList, (*it).name(), TQString(), (*it).id());
    p->setRenameEnabled(0, true);

    if((*it).id() == baseCurrency) {
      p->setPixmap(0, TQPixmap( locate("icon","hicolor/16x16/apps/kmymoney2.png")));
      if(m_currency.id().isEmpty())
        first = p;
    } else {
      p->setPixmap(0, empty);
    }

    // if we had a previously selected
    if(!m_currency.id().isEmpty()) {
      if(m_currency.id() == p->id())
        first = p;
    } else if ((*it).id() == localCurrency && !first)
      first = p;
  }

  if(first == 0)
    first = m_currencyList->firstChild();
  if(first != 0) {
    m_currencyList->setSelected(first, true);
    m_currencyList->ensureItemVisible(first);
  }

  slotSelectCurrency(first);
}

void KCurrencyEditDlg::updateCurrency(void)
{
  if(!m_currency.id().isEmpty()) {
    if(m_symbolEdit->text() != m_currency.tradingSymbol()) {
      m_currency.setTradingSymbol(m_symbolEdit->text());
      MyMoneyFileTransaction ft;
      try {
        MyMoneyFile::instance()->modifyCurrency(m_currency);
        ft.commit();
      } catch(MyMoneyException *e) {
        tqWarning("Updateing the currency failed!");
        delete e;
      }
    }
  }
}

void KCurrencyEditDlg::slotSelectCurrency(const TQString& id)
{
  TQListViewItemIterator it(m_currencyList);

  while(it.current()) {
    KMyMoneyListViewItem* p = static_cast<KMyMoneyListViewItem*>(it.current());
    if(p->id() == id) {
      slotSelectCurrency(p);
      m_currencyList->setSelected(p, true);
      m_currencyList->ensureItemVisible(p);
      break;
    }
    ++it;
  }
}

void KCurrencyEditDlg::slotSelectCurrency(TQListViewItem *item)
{
  TQMap<TQDate, MyMoneyMoney> history;
  MyMoneyFile* file = MyMoneyFile::instance();

  updateCurrency();

  m_detailGroup->setEnabled(item != 0);
  m_onlineSourceTable->clear();
  m_idLabel->setText(TQString());
  m_symbolEdit->setText(TQString());

  if(item) {
    try {
      KMyMoneyListViewItem* p = static_cast<KMyMoneyListViewItem *>(item);
      m_currency = file->security(p->id());
      m_idLabel->setText(m_currency.id());
      m_symbolEdit->setText(m_currency.tradingSymbol());

    } catch(MyMoneyException *e) {
      delete e;
      m_currency = MyMoneySecurity();
      m_onlineSourceTable->clear();
      m_idLabel->setText(TQString());
      m_symbolEdit->setText(TQString());
    }
    m_baseCurrencyButton->setDisabled(m_currency.id() == file->baseCurrency().id());
    emit selectObject(m_currency);
  }
}

void KCurrencyEditDlg::slotClose(void)
{
  updateCurrency();
  accept();
}

void KCurrencyEditDlg::slotStartRename(void)
{
  TQListViewItemIterator it_l(m_currencyList, TQListViewItemIterator::Selected);
  TQListViewItem* it_v;
  if((it_v = it_l.current()) != 0) {
    it_v->startRename(0);
  }
}

void KCurrencyEditDlg::slotListClicked(TQListViewItem* item, const TQPoint&, int)
{
  slotSelectCurrency(item);
  emit openContextMenu(m_currency);
}

void KCurrencyEditDlg::slotRenameCurrency(TQListViewItem* item, int /* col */, const TQString& txt)
{
  MyMoneyFile* file = MyMoneyFile::instance();
  KMyMoneyListViewItem* p = static_cast<KMyMoneyListViewItem *>(item);

  try {
    if(txt != m_currency.name()) {
      tqDebug("Renaming");
      MyMoneySecurity currency = file->currency(p->id());
      currency.setName(txt);
      MyMoneyFileTransaction ft;
      try {
        file->modifyCurrency(currency);
        m_currency = currency;
        ft.commit();
      } catch(MyMoneyException* e) {
        tqDebug("Renaming currency failed");
        delete e;
      }
    }
  } catch(MyMoneyException *e) {
    delete e;
    updateCurrency();
  }
}

void KCurrencyEditDlg::slotSelectBaseCurrency(void)
{
  if(!m_currency.id().isEmpty()) {
    TQListViewItem* p = m_currencyList->selectedItem();
    emit selectBaseCurrency(m_currency);
    // in case the dataChanged() signal was not sent out (nested FileTransaction)
    // we update the list manually
    if(p == m_currencyList->selectedItem())
      slotLoadCurrencies();
  }
}

#include "kcurrencyeditdlg.moc"
