/***************************************************************************
                         kofxdirectconnectdlg.cpp
                             -------------------
    begin                : Sat Nov 13 2004
    copyright            : (C) 2002 by Ace Jones
    email                : acejones@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 <tqlabel.h>
#include <tqdir.h>
#include <tqfile.h>
#include <tqtextstream.h>

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

#include <kurl.h>
#include <tdeio/job.h>
#include <tdeio/jobclasses.h>
#include <kdebug.h>
#include <tdetempfile.h>
#include <kprogress.h>
#include <tdemessagebox.h>
#include <tdelocale.h>

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

#include <kmymoney/mymoneyinstitution.h>
#include <kmymoney/mymoneyfile.h>
#include "mymoneyofxconnector.h"
#include "kofxdirectconnectdlg.h"


class KOfxDirectConnectDlg::Private
{
public:
  TQFile    m_fpTrace;
};

KOfxDirectConnectDlg::KOfxDirectConnectDlg(const MyMoneyAccount& account, TQWidget *parent, const char *name) :
  KOfxDirectConnectDlgDecl(parent, name),
  d(new Private),
  m_tmpfile(NULL),
  m_connector(account),
  m_job(NULL)
{
}

KOfxDirectConnectDlg::~KOfxDirectConnectDlg()
{
  if(d->m_fpTrace.isOpen()) {
    d->m_fpTrace.close();
  }
  delete m_tmpfile;
  delete d;
}

void KOfxDirectConnectDlg::init(void)
{
  show();

  TQByteArray request = m_connector.statementRequest();

  // For debugging, dump out the request
#if 0
  TQFile g( "request.ofx" );
  g.open( IO_WriteOnly );
  TQTextStream(&g) << m_connector.url() << "\n" << TQString(request);
  g.close();
#endif

  TQDir homeDir(TQDir::home());
  if(homeDir.exists("ofxlog.txt")) {
    d->m_fpTrace.setName(TQString("%1/ofxlog.txt").arg(TQDir::homeDirPath()));
    d->m_fpTrace.open(IO_WriteOnly | IO_Append);
  }

  m_job = TDEIO::http_post(
    m_connector.url(),
    request,
    true
  );
  if(d->m_fpTrace.isOpen()) {
    TQByteArray data = m_connector.url().utf8();
    d->m_fpTrace.writeBlock("url: ", 5);
    d->m_fpTrace.writeBlock(data, strlen(data));
    d->m_fpTrace.writeBlock("\n", 1);
    d->m_fpTrace.writeBlock("request:\n", 9);
    d->m_fpTrace.writeBlock(request, request.size());
    d->m_fpTrace.writeBlock("\n", 1);
    d->m_fpTrace.writeBlock("response:\n", 10);
  }

  m_job->addMetaData("content-type", "Content-type: application/x-ofx" );
  connect(m_job,TQ_SIGNAL(result(TDEIO::Job*)),this,TQ_SLOT(slotOfxFinished(TDEIO::Job*)));
  connect(m_job,TQ_SIGNAL(data(TDEIO::Job*, const TQByteArray&)),this,TQ_SLOT(slotOfxData(TDEIO::Job*,const TQByteArray&)));
  connect(m_job,TQ_SIGNAL(connected(TDEIO::Job*)),this,TQ_SLOT(slotOfxConnected(TDEIO::Job*)));

  setStatus(TQString("Contacting %1...").arg(m_connector.url()));
  kProgress1->setTotalSteps(3);
  kProgress1->setProgress(1);
}

void KOfxDirectConnectDlg::setStatus(const TQString& _status)
{
  textLabel1->setText(_status);
  kdDebug(2) << "STATUS: " << _status << endl;
}

void KOfxDirectConnectDlg::setDetails(const TQString& _details)
{
  kdDebug(2) << "DETAILS: " << _details << endl;
}

void KOfxDirectConnectDlg::slotOfxConnected(TDEIO::Job*)
{
  if ( m_tmpfile )
  {
//     throw new MYMONEYEXCEPTION(TQString("Already connected, using %1.").arg(m_tmpfile->name()));
    kdDebug(2) << "Already connected, using " << m_tmpfile->name() << endl;
    delete m_tmpfile; //delete otherwise we mem leak
  }
  m_tmpfile = new KTempFile();
  setStatus("Connection established, retrieving data...");
  setDetails(TQString("Downloading data to %1...").arg(m_tmpfile->name()));
  kProgress1->advance(1);
}

void KOfxDirectConnectDlg::slotOfxData(TDEIO::Job*,const TQByteArray& _ba)
{
  if ( !m_tmpfile )
//     throw new MYMONEYEXCEPTION("Not currently connected!!");
    kdDebug(2) << "void ofxdcon::slotOfxData():: Not currently connected!" << endl;
  *(m_tmpfile->textStream()) << TQString(_ba);

  if(d->m_fpTrace.isOpen()) {
    d->m_fpTrace.writeBlock(_ba, _ba.size());
  }

  setDetails(TQString("Got %1 bytes").arg(_ba.size()));
}

void KOfxDirectConnectDlg::slotOfxFinished(TDEIO::Job* /* e */)
{
  kProgress1->advance(1);
  setStatus("Completed.");

  if(d->m_fpTrace.isOpen()) {
    d->m_fpTrace.writeBlock("\nCompleted\n\n\n\n", 14);
  }

  int error = m_job->error();

  if ( m_tmpfile )
  {
    m_tmpfile->close();
  }

  if ( error )
  {
    m_job->showErrorDialog();
  }
  else if ( m_job->isErrorPage() )
  {
    TQString details;
    TQFile f( m_tmpfile->name() );
    if ( f.open( IO_ReadOnly ) )
    {
      TQTextStream stream( &f );
      TQString line;
      while ( !stream.atEnd() ) {
          details += stream.readLine(); // line of text excluding '\n'
      }
      f.close();

      kdDebug(2) << "The HTTP request failed: " << details << endl;
    }
    KMessageBox::detailedSorry( this, i18n("The HTTP request failed."), details, i18n("Failed") );
  }
  else if ( m_tmpfile )
  {

    emit statementReady(m_tmpfile->name());

// TODO (Ace) unlink this file, when I'm sure this is all really working.
// in the meantime, I'll leave the file around to assist people in debugging.
//     m_tmpfile->unlink();
  }
  delete m_tmpfile;
  m_tmpfile = 0;
  hide();
}

void KOfxDirectConnectDlg::reject(void)
{
  m_job->kill();
  if ( m_tmpfile )
  {
    m_tmpfile->close();
    delete m_tmpfile;
    m_tmpfile = NULL;
  }
  TQDialog::reject();
}

#include "kofxdirectconnectdlg.moc"
