/***************************************************************************
                          kenterscheduledlg.cpp
                             -------------------
    begin                : Sat Apr  7 2007
    copyright            : (C) 2007 by Thomas Baumgart
    email                : 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 Includes

#include <tqtimer.h>
#include <tqwidgetlist.h>
#include <tqlabel.h>

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

#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kpushbutton.h>
#include <kstdguiitem.h>
#include <kiconloader.h>

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

#include "kenterscheduledlg.h"
#include "../dialogs/kcurrencycalculator.h"
#include <kmymoney/register.h>
#include <kmymoney/transactionform.h>
#include <kmymoney/transaction.h>
#include <kmymoney/transactioneditor.h>
#include <kmymoney/kmymoneyutils.h>
#include <kmymoney/mymoneyfinancialcalculator.h>
#include <kmymoney/kmymoneylineedit.h>
#include <kmymoney/kmymoneycategory.h>
#include <kmymoney/kmymoneyaccountselector.h>
#include <kmymoney/kmymoneydateinput.h>

#include "../kmymoney2.h"

class KEnterScheduleDlg::Private
{
public:
  Private() : m_item(0), m_showWarningOnce(true) {}
  ~Private() {}

  MyMoneySchedule                m_schedule;
  KMyMoneyRegister::Transaction* m_item;
  TQWidgetList                    m_tabOrderWidgets;
  bool                           m_showWarningOnce;
  KMyMoneyUtils::EnterScheduleResultCodeE m_extendedReturnCode;
};

KEnterScheduleDlg::KEnterScheduleDlg(TQWidget *parent, const MyMoneySchedule& schedule) :
  KEnterScheduleDlgDecl(parent, "kenterscheduledlg"),
  d(new Private)
{
  d->m_schedule = schedule;
  d->m_extendedReturnCode = KMyMoneyUtils::Enter;
  buttonOk->setIconSet(TDEGlobal::iconLoader()->loadIconSet("key_enter", TDEIcon::NoGroup, TDEIcon::SizeSmall, true));
  buttonSkip->setIconSet(TDEGlobal::iconLoader()->loadIconSet("media-seek-forward", TDEIcon::NoGroup, TDEIcon::SizeSmall, true));
  buttonCancel->setGuiItem(KStdGuiItem::cancel());
  buttonHelp->setGuiItem(KStdGuiItem::help());
  buttonIgnore->setHidden(true);
  buttonSkip->setHidden(true);

  // make sure, we have a tabbar with the form
  KMyMoneyTransactionForm::TabBar* tabbar = m_form->tabBar(m_form->parentWidget());

  // we never need to see the register
  m_register->hide();

  // ... setup the form ...
  m_form->setupForm(d->m_schedule.account());

  // ... and the register ...
  m_register->clear();

  // ... now add the transaction to register and form ...
  MyMoneyTransaction t = transaction();
  d->m_item = KMyMoneyRegister::Register::transactionFactory(m_register, t, d->m_schedule.transaction().splits()[0], 0);
  m_register->selectItem(d->m_item);
  // show the account row
  d->m_item->setShowRowInForm(0, true);

  m_form->slotSetTransaction(d->m_item);

  // no need to see the tabbar
  tabbar->hide();

  // setup name and type
  m_scheduleName->setText(d->m_schedule.name());
  m_type->setText(KMyMoneyUtils::scheduleTypeToString(d->m_schedule.type()));

  connect(buttonHelp, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotShowHelp()));
  connect(buttonIgnore, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotIgnore()));
  connect(buttonSkip, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotSkip()));

  // force the initial height to be as small as possible
  TQTimer::singleShot(0, this, TQ_SLOT(slotSetupSize()));
}

KEnterScheduleDlg::~KEnterScheduleDlg()
{
  delete d;
}

KMyMoneyUtils::EnterScheduleResultCodeE KEnterScheduleDlg::resultCode(void) const
{
  if(result() == TQDialog::Accepted)
    return d->m_extendedReturnCode;
  return KMyMoneyUtils::Cancel;
}

void KEnterScheduleDlg::showExtendedKeys(bool visible)
{
  buttonIgnore->setShown(visible);
  buttonSkip->setShown(visible);
}

void KEnterScheduleDlg::slotIgnore(void)
{
  d->m_extendedReturnCode = KMyMoneyUtils::Ignore;
  accept();
}

void KEnterScheduleDlg::slotSkip(void)
{
  d->m_extendedReturnCode = KMyMoneyUtils::Skip;
  accept();
}

MyMoneyTransaction KEnterScheduleDlg::transaction(void)
{
  MyMoneyTransaction t = d->m_schedule.transaction();

  try {
    if (d->m_schedule.type() == MyMoneySchedule::TYPE_LOANPAYMENT) {
      KMyMoneyUtils::calculateAutoLoan(d->m_schedule, t, TQMap<TQString, MyMoneyMoney>());
    }
  } catch (MyMoneyException* e) {
    KMessageBox::detailedError(this, i18n("Unable to load schedule details"), e->what());
    delete e;
  }

  t.clearId();
  t.setEntryDate(TQDate());
  return t;
}

TQDate KEnterScheduleDlg::date(const TQDate& _date) const
{
  TQDate date(_date);
  return d->m_schedule.adjustedDate(date, d->m_schedule.weekendOption());
}

void KEnterScheduleDlg::resizeEvent(TQResizeEvent* ev)
{
  m_register->resize(KMyMoneyRegister::DetailColumn);
  m_form->resize(KMyMoneyTransactionForm::ValueColumn1);
  KEnterScheduleDlgDecl::resizeEvent(ev);
}


void KEnterScheduleDlg::slotSetupSize(void)
{
  resize(width(), minimumSizeHint().height());
}

int KEnterScheduleDlg::exec(void)
{
  if(d->m_showWarningOnce) {
    d->m_showWarningOnce = false;
    KMessageBox::information(this, TQString("<qt>")+i18n("<p>Please check that all the details in the following dialog are correct and press OK.</p><p>Editable data can be changed and can either be applied to just this occurence or for all subsequent occurences for this schedule.  (You will be asked what you intend after pressing OK in the following dialog)</p>")+TQString("</qt>"), i18n("Enter scheduled transaction"), "EnterScheduleDlgInfo");
  }

  return KEnterScheduleDlgDecl::exec();
}

TransactionEditor* KEnterScheduleDlg::startEdit(void)
{
  KMyMoneyRegister::SelectedTransactions list(m_register);
  TransactionEditor* editor = d->m_item->createEditor(m_form, list, TQDate());

  // check that we use the same transaction commodity in all selected transactions
  // if not, we need to update this in the editor's list. The user can also bail out
  // of this operation which means that we have to stop editing here.
  if(editor) {
    if(!editor->fixTransactionCommodity(d->m_schedule.account())) {
      // if the user wants to quit, we need to destroy the editor
      // and bail out
      delete editor;
      editor = 0;
    }
  }

  if(editor) {
    connect(editor, TQ_SIGNAL(transactionDataSufficient(bool)), buttonOk, TQ_SLOT(setEnabled(bool)));
    connect(editor, TQ_SIGNAL(escapePressed()), buttonCancel, TQ_SLOT(animateClick()));
    connect(editor, TQ_SIGNAL(returnPressed()), buttonOk, TQ_SLOT(animateClick()));

    connect(MyMoneyFile::instance(), TQ_SIGNAL(dataChanged()), editor, TQ_SLOT(slotReloadEditWidgets()));
    // connect(editor, TQ_SIGNAL(finishEdit(const KMyMoneyRegister::SelectedTransactions&)), this, TQ_SLOT(slotLeaveEditMode(const KMyMoneyRegister::SelectedTransactions&)));
    connect(editor, TQ_SIGNAL(createPayee(const TQString&, TQString&)), kmymoney2, TQ_SLOT(slotPayeeNew(const TQString&, TQString&)));
    connect(editor, TQ_SIGNAL(createCategory(MyMoneyAccount&, const MyMoneyAccount&)), kmymoney2, TQ_SLOT(slotCategoryNew(MyMoneyAccount&, const MyMoneyAccount&)));
    connect(editor, TQ_SIGNAL(createSecurity(MyMoneyAccount&, const MyMoneyAccount&)), kmymoney2, TQ_SLOT(slotInvestmentNew(MyMoneyAccount&, const MyMoneyAccount&)));
    connect(MyMoneyFile::instance(), TQ_SIGNAL(dataChanged()), editor, TQ_SLOT(slotReloadEditWidgets()));

    // create the widgets, place them in the parent and load them with data
    // setup tab order
    d->m_tabOrderWidgets.clear();
    KMyMoneyRegister::Action action = KMyMoneyRegister::ActionWithdrawal;
    switch(d->m_schedule.type()) {
      case MyMoneySchedule::TYPE_DEPOSIT:
        action = KMyMoneyRegister::ActionDeposit;
        break;
      case MyMoneySchedule::TYPE_TRANSFER:
        action = KMyMoneyRegister::ActionTransfer;
        break;
      case MyMoneySchedule::TYPE_LOANPAYMENT:
        switch(d->m_schedule.paymentType()) {
          case MyMoneySchedule::STYPE_DIRECTDEPOSIT:
          case MyMoneySchedule::STYPE_MANUALDEPOSIT:
            action = KMyMoneyRegister::ActionDeposit;
            break;
          default:
            break;
        }
        break;
      default:
        break;
    }
    editor->setup(d->m_tabOrderWidgets, d->m_schedule.account(), action);

    // if it's not a check, then we need to clear
    // a possibly assigned check number
    if(d->m_schedule.paymentType() != MyMoneySchedule::STYPE_WRITECHEQUE) {
      TQWidget* w = editor->haveWidget("number");
      if(w)
        dynamic_cast<kMyMoneyLineEdit*>(w)->loadText(TQString());
    }

    Q_ASSERT(!d->m_tabOrderWidgets.isEmpty());

    // don't forget our three buttons
    d->m_tabOrderWidgets.append(buttonOk);
    d->m_tabOrderWidgets.append(buttonCancel);
    d->m_tabOrderWidgets.append(buttonHelp);

    // install event filter in all taborder widgets
    for(TQWidget* w = d->m_tabOrderWidgets.first(); w; w = d->m_tabOrderWidgets.next()) {
      w->installEventFilter(this);
      w->installEventFilter(editor);
    }

    // Check if the editor has some preference on where to set the focus
    // If not, set the focus to the first widget in the tab order
    TQWidget* focusWidget = editor->firstWidget();
    if(!focusWidget)
      focusWidget = d->m_tabOrderWidgets.first();
    focusWidget->setFocus();

    // Make sure, we use the adjusted date
    kMyMoneyDateInput* dateEdit = dynamic_cast<kMyMoneyDateInput*>(editor->haveWidget("postdate"));
    if(dateEdit) {
      dateEdit->setDate(d->m_schedule.adjustedNextDueDate());
    }
  }

  return editor;
}

bool KEnterScheduleDlg::focusNextPrevChild(bool next)
{
  bool  rc = false;

  // tqDebug("TDEGlobalLedgerView::focusNextPrevChild(editmode=%s)", m_inEditMode ? "true" : "false");
  TQWidget *w = 0;
  TQWidget *currentWidget;

  w = tqApp->focusWidget();
  while(w && d->m_tabOrderWidgets.find(w) == -1) {
    // tqDebug("'%s' not in list, use parent", w->className());
    w = w->parentWidget();
  }
  // if(w) tqDebug("tab order is at '%s'", w->className());
  currentWidget = d->m_tabOrderWidgets.current();
  w = next ? d->m_tabOrderWidgets.next() : d->m_tabOrderWidgets.prev();

  do {
    if(!w) {
      w = next ? d->m_tabOrderWidgets.first() : d->m_tabOrderWidgets.last();
    }

    if(w != currentWidget
    && ((w->focusPolicy() & TQWidget::TabFocus) == TQWidget::TabFocus)
    && w->isVisible() && w->isEnabled()) {
      // tqDebug("Selecting '%s' as focus", w->className());
      w->setFocus();
      rc = true;
      break;
    }
    w = next ? d->m_tabOrderWidgets.next() : d->m_tabOrderWidgets.prev();
  } while(w != currentWidget);

  return rc;
}

void KEnterScheduleDlg::slotShowHelp(void)
{
  kapp->invokeHelp("details.schedules.entering");
}


#include "kenterscheduledlg.moc"

