/***************************************************************************
**
**  This file is part of QGpGuiTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2007-01-05
**  Copyright: 2007-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <QtGui>
#include <QtNetwork>
#include <QGpCoreTools.h>

#include "BugReport.h"
#include "Application.h"
#include "HttpAccess.h"
#include "Attachments.h"

namespace QGpGuiTools {

  /*!
  */
  BugReport::BugReport(QWidget* parent, Qt::WindowFlags fl)
      : Dialog(parent, fl)
  {
    TRACE;
    setupUi(this);
    QSettings& reg=CoreApplication::instance()->globalSettings();
    from->setPlaceholderText("Enter here YOUR email address");
    if(reg.contains("usermail")) {
      from->setText(reg.value("usermail").toString());
    }
    Settings::getRect(this, "BugReport");
    infoContent->setFont(QFont("Monospace"));

    comments->setPlaceholderText("-- Enter here optional comments --\n"
                                 "This application shouldn't crash, so don't be afraid of sending this "
                                 "report even if you think that you've done something wrong, in fact, what's "
                                 "wrong is the developer's job.\n"
                                 "\n"
                                 "- Can you reproduce the application crash?\n"
                                 "- How did it happen?\n"
                                 "- Did it happen reading an input file? Can you attach it (see 'Attachments' here below)?\n");

    _access=new HttpAccess("http://www.geopsy.org/access_testing.txt", this);
    connect(_access, SIGNAL(finished(bool)), this, SLOT(sent(bool)));
  }

  /*!

  */
  BugReport::~BugReport()
  {
    TRACE;
    QSettings& reg=CoreApplication::instance()->globalSettings();
    reg.setValue("usermail",from->text());
    delete _access;
    Settings::setRect(this, "BugReport");
  }

  void BugReport::setInfo(const QString& bugInfo)
  {
    TRACE;
    infoContent->setPlainText(bugInfo);
  }

  void BugReport::on_saveBut_clicked()
  {
    TRACE;
    QString fileName=Message::getSaveFileName("Save bug report", "Bug report (*.html)");
    if(!fileName.isEmpty()) {
      QFile f(fileName);
      if(f.open(QIODevice::WriteOnly)) {
        QTextStream s(&f);
        QString cmt=encodeToHtml(comments->toPlainText());
        s << Application::htmlBugReport(encodeToHtml(infoContent->toPlainText()),
                                        from->text(), cmt);
      }
    }
  }

  void BugReport::on_sendBut_clicked()
  {
    TRACE;
    send();
  }

  void BugReport::send()
  {
    TRACE;
    QString email=from->text();
    if(!email.contains("@")) {
      Message::warning(MSG_ID, tr("Sending bug report"), tr("Not a valid e-mail"));
      return;
    }
    setGuiEnable(false);
    //QStringList files(_attachments);
    _access->post(QUrl("http://www.geopsy.org/bugs/backtrace.php"), bugInfo());
  }

  QByteArray BugReport::bugInfo()
  {
    TRACE;
    QByteArray data;
    data+="userid=";
    data+=QByteArray::number(CoreApplication::userId());
    data+="&email=";
    data+=QUrl::toPercentEncoding(from->text());
    data+="&systemInfo=";
    data+=QUrl::toPercentEncoding(infoContent->toPlainText());
    data+="&userInfo=";
    data+=QUrl::toPercentEncoding(comments->toPlainText());
    return data;
  }

  void BugReport::sent(bool ok)
  {
    TRACE;
    if(ok) {
      QString info=_access->receivedData();
      QRegExp reg("<!--BEGIN BUG MESSAGE-->(.*)<!--END BUG MESSAGE-->");
      reg.indexIn(info);
      QString msg=reg.cap(1);
      if(msg.contains("uccessful")) {
        Message::information(MSG_ID, tr("geopsy.org bug report"), "<html><body>"+msg+"</body></html>");
        QApplication::quit();
      } else {
        Message::warning(MSG_ID, tr("geopsy.org bug report"), "<html><body>"+msg+"</body></html>");
      }
    } else {
      Message::warning(MSG_ID, tr("geopsy.org bug report"),
                           tr("<html><body><p>Cannot send bug report. To help debugging, please try to "
                              "<a href=\"http://www.geopsy.org/bugs/backtrace.php?%1\">submit it manually</a>. "
                              " By clicking on this link, your browser will be opened. If you are not connected to the network now, click on 'Save'. "
                              "A .html file will be generated, open it in your web browser the next time your are connected.</p>")
                           .arg(QString(bugInfo())));

    }
    setGuiEnable(true);
  }

  void BugReport::setGuiEnable(bool e)
  {
    sendBut->setEnabled(e);
    from->setEnabled(e);
    comments->setEnabled(e);
    //attach->setEnabled(e);
  }

  void BugReport::on_attach_clicked()
  {
    TRACE;
    Attachments * d=new Attachments(this);
    d->setFileList(_attachments);
    if(d->exec()==QDialog::Accepted) {
      _attachments=d->getFileList();
    }
  }

} // namespace QGpGuiTools
