/*
 * This file is part of the xTuple ERP: PostBooks Edition, a free and
 * open source Enterprise Resource Planning software suite,
 * Copyright (c) 1999-2009 by OpenMFG LLC, d/b/a xTuple.
 * It is licensed to you under the Common Public Attribution License
 * version 1.0, the full text of which (including xTuple-specific Exhibits)
 * is available at www.xtuple.com/CPAL.  By using this software, you agree
 * to be bound by its terms.
 */

#include "deliverPurchaseOrder.h"

#include <qvariant.h>
#include <qmessagebox.h>

/*
 *  Constructs a deliverPurchaseOrder as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog.
 */
deliverPurchaseOrder::deliverPurchaseOrder(QWidget* parent, const char* name, bool modal, Qt::WFlags fl)
    : XDialog(parent, name, modal, fl)
{
    setupUi(this);


    // signals and slots connections
    connect(_submit, SIGNAL(clicked()), this, SLOT(sSubmit()));
    connect(_close, SIGNAL(clicked()), this, SLOT(reject()));
    connect(_po, SIGNAL(newId(int)), this, SLOT(sHandlePoheadid(int)));
    init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
deliverPurchaseOrder::~deliverPurchaseOrder()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void deliverPurchaseOrder::languageChange()
{
    retranslateUi(this);
}


void deliverPurchaseOrder::init()
{
  _captive = FALSE;
  
  _po->setType(cPOUnposted | cPOOpen);

  q.exec( "SELECT usr_email "
          "FROM usr "
          "WHERE (usr_username=CURRENT_USER);" );
  if (q.first())
    _fromEmail->setText(q.value("usr_email"));
//  ToDo
}

enum SetResponse deliverPurchaseOrder::set(ParameterList &pParams)
{
  _captive = TRUE;

  QVariant param;
  bool     valid;

  param = pParams.value("pohead_id", &valid);
  if (valid)
  {
    _po->setId(param.toInt());
    _submit->setFocus();
  }

  return NoError;
}

void deliverPurchaseOrder::sSubmit()
{
  if (_email->text().isEmpty())
  {
    QMessageBox::critical( this, tr("Cannot Queue P/O for Delivery"),
                           tr("You must enter a email address to which this P/O is to be delivered.") );
    _email->setFocus();
    return;
  }

  q.prepare( "SELECT submitReportToBatch( 'PurchaseOrder', :fromEmail, :emailAddress, :ccAddress, :subject,"
             "                            :emailBody, :fileName, CURRENT_TIMESTAMP, :emailhtml) AS batch_id;" );
  q.bindValue(":fromEmail", _fromEmail->text());
  q.bindValue(":emailAddress", _email->text());
  q.bindValue(":ccAddress", _cc->text());
  q.bindValue(":subject", _subject->text());
  q.bindValue(":fileName", _fileName->text());
  q.bindValue(":emailBody", _emailBody->toPlainText());
  q.bindValue(":emailhtml", QVariant(_emailHTML->isChecked()));
  q.exec();
  if (q.first())
  {
    int batchid = q.value("batch_id").toInt();

    q.prepare( "INSERT INTO batchparam "
               "( batchparam_batch_id, batchparam_order,"
               "  batchparam_name, batchparam_value ) "
               "VALUES "
               "( :batchparam_batch_id, :batchparam_order,"
               "  :batchparam_name, :batchparam_value );" );

    q.bindValue(":batchparam_batch_id", batchid);
    q.bindValue(":batchparam_order", 1);
    q.bindValue(":batchparam_name", "pohead_id");
    q.bindValue(":batchparam_value", _po->id());
    q.exec();

    q.bindValue(":batchparam_batch_id", batchid);
    q.bindValue(":batchparam_order", 2);
    q.bindValue(":batchparam_name", "title");
    q.bindValue(":batchparam_value", "Emailed Vendor Copy");
    q.exec();
  }

  if (_markPrinted->isChecked())
  {
    q.prepare( "UPDATE pohead "
               "SET pohead_printed=TRUE "
               "WHERE (pohead_id=:pohead_id);" );
    q.bindValue(":pohead_id", _po->id());
    q.exec();
  }

  if (_captive)
    accept();
  else
  {
    _submit->setEnabled(FALSE);
    _close->setText(tr("&Close"));
    _email->clear();
    _cc->clear();
    _emailBody->clear();
    _subject->clear();
    _fileName->clear();
    _po->setId(-1);
    _po->setFocus();
  }
}

void deliverPurchaseOrder::sHandlePoheadid(int pPoheadid)
{
  q.prepare( "SELECT vend_emailpodelivery, vend_ediemail, vend_ediemailbody, "
             "       vend_edisubject, vend_edifilename, vend_edicc, vend_ediemailhtml "
             "FROM pohead, vendinfo "
             "WHERE ( (pohead_vend_id=vend_id)"
             " AND (pohead_id=:pohead_id) );" );
  q.bindValue(":pohead_id", pPoheadid);
  q.exec();
  if (q.first())
  {
    if (q.value("vend_emailpodelivery").toBool())
    {
      _submit->setEnabled(TRUE);
      _email->setText(q.value("vend_ediemail"));
      _cc->setText(q.value("vend_edicc").toString());
      _emailBody->setPlainText(q.value("vend_ediemailbody").toString().replace("</docnumber>", _po->poNumber()).replace("</doctype>", "PO"));
      _subject->setText(q.value("vend_edisubject").toString().replace("</docnumber>", _po->poNumber()).replace("</doctype>", "PO"));
      _fileName->setText(q.value("vend_edifilename").toString().replace("</docnumber>", _po->poNumber()).replace("</doctype>", "PO"));
      _emailHTML->setChecked(q.value("vend_ediemailhtml").toBool());
    }
    else
    {
      _submit->setEnabled(FALSE);
      _email->clear();
      _cc->clear();
      _emailBody->clear();
      _subject->clear();
      _fileName->clear();
    }
  }
}
