/* -*- C++ -*-

Copyright (C) 2000-20022 Francesco Bresciani <fbresciani@users.sourceforge.net>
This file is part of Kemistry

Kemistry 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, or (at your option)
any later version.

Kemistry 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Kemistry; see the file COPYING.  If not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/


#include "kmolcalcwidget.h"
#include "kmolcalceditor.h"

#include <kfiledialog.h>
#include <klineedit.h>
#include <klocale.h>
#include <kapp.h>
#include <qtextbrowser.h>
#include <kio/netaccess.h>
#include <qcheckbox.h>
#include <kconfig.h>
#include <kpushbutton.h>
#include <khelpmenu.h>
#include <kapplication.h>
#include <kpopupmenu.h>

#include <kdebug.h>

#include "kemistry-openbabel.h"

KMolCalcWidget::KMolCalcWidget(QWidget *parent)
  : KMolCalcWidgetBase(parent, "MMCALC_WIDGET")
{
    readConfig();

    KHelpMenu *helpMenu = new KHelpMenu(this, KGlobal::instance()->aboutData(), false);
    _btnHelp->setPopup(helpMenu->menu());

}

KMolCalcWidget::~KMolCalcWidget()
{
	writeConfig();
}

void KMolCalcWidget::slotEditor()
{
  static KMolCalcEditorDlg *editor = 0L;
  if (editor)
    editor->show();
  else
  {
    editor = new KMolCalcEditorDlg(this);
    editor->show();
  }
}

void KMolCalcWidget::slotCompute()
{
  if (!(_editFormula->text().isEmpty()))
  {
    _parser.parseFormula(_editFormula->text());
    QString errormsg = _parser.errorMessage();
    if (errormsg == QString::null)
    {
      QMap<QString, double> result;
      double mass;
      _parser.computeMassAndElemPercent(mass, result);
      displayResults(_editFormula->text(), mass, result);
    }
    else
      errorMessage(errormsg);
  }
}


void KMolCalcWidget::errorMessage(const QString& message)
{
  // Clear the QTextView output widget
  _output->setText(QString::null);

  // display error message in red
  QString text = "<qt text=\"red\">";
  text += "<center><h2>"+ i18n("Error Message!")+"</h2></center><br/><br/>";
  text += message;
  text += "</qt>";

  _output->setText(text);
}

void KMolCalcWidget::displayResults(const QString& formula, double mass,
                                  const QMap<QString, double>& percent)
{
  _output->setText(QString::null);

  QString text = "<qt text=black><center><h3>";
  text += i18n("Results:")+"</h3></center>";
  text += "<br/>";

  text += i18n("<b>Parsed formula: </b> ");
	// display parsed formula
  for (uint i = 0; i < formula.length(); i++)
    if (formula[i].isDigit())
      text += QString("<small>")+formula[i]+QString("</small>");
    else
      text += formula[i];
  text += "<br/>";
  text += i18n("<b>Molecular weight:</b> %1 g/mol").arg(mass, 8, 'f', 4);
  text += "<br/>";
  text += i18n("<h3>Elemental composition:</h3>");
  text += "<table border=1><tr>";
  text += i18n("<td>Element</td><td>Percentage</td>");

  QMap<QString, double>::ConstIterator it;
  for (it = percent.begin(); it != percent.end(); ++it)
    text += QString("<tr><td>%1</td><td>%2%</td></tr>").arg(it.key()).
            arg(it.data(), 8, 'f', 3);
  text += "</tr></table>";
  text += "</qt>";
  _output->setText(text);
}

void KMolCalcWidget::displayResultsFile(const QString& url, double mass,
	const QMap<QString, double>& percent, const QMap<QString, double>& count)
{
  _output->setText(QString::null);

  QString text = "<qt text=black><center><h3>";
  text += i18n("Results:")+"</h3></center>";
  text += "<br/>";

  text += i18n("<b>Parsed file URL: </b> ");
  text += QString("<br/>%1<br/>").arg(url);
  text += "<br/>";
  text += i18n("<b>Parsed formula: </b>");
  text += QString("C<small>%1</small>H<small>%2</small>").arg(count["C"])
          .arg(count["H"]);
  QMap<QString, double>::ConstIterator it;
  for (it = count.begin(); it != count.end(); ++it)
  {
    if (it.key() == "C" || it.key() == "H")
      continue;
    text += QString("%1<small>%2</small>").arg(it.key()).arg(it.data());
  }
  text += "<br/>";
  text += i18n("<b>Molecular weight:</b> %1 g/mol").arg(mass, 8, 'f', 4);
  text += "<br/>";
  text += i18n("<h3>Elemental composition:</h3>");
  text += "<table border=1><tr>";
  text += i18n("<td><center>Element</center></td><td><center>"
		  "Percentage</center></td>");

  for (it = percent.begin(); it != percent.end(); ++it)
    text += QString("<tr><td>%1</td><td>%2%</td></tr>").arg(it.key()).
            arg(it.data(), 8, 'f', 3);
  text += "</tr></table>";
  text += "</qt>";
  _output->setText(text);
}

void KMolCalcWidget::slotLoadFileCompute()
{
    static KFileDialog* dialog = 0L;
  QMap<QString, double> result;
  double mass;
  QString mime, tmpfile;
  //obtain the list of mime types supported by Open Babel
  Kemistry::getOBReadMimeTypes(mime);
  if (!dialog)
      dialog = new KFileDialog("", mime, this, "file_dialog", false);
  dialog->exec();
  KURL url = dialog->selectedURL();

  if (!url.isEmpty())
  {
      if (url.isLocalFile())
      {
          tmpfile = url.directory()+"/"+url.filename();
      }
      else
          if (!KIO::NetAccess::download(url,tmpfile))
          {
              errorMessage(i18n("Cannot download  '%1'").arg(url.prettyURL()));
              return;
          }

      _parser.parseFile(tmpfile);
      QString errormsg = _parser.errorMessage();
      if (errormsg == QString::null)
      {
          _parser.computeMassAndElemPercent(mass, result);
          displayResultsFile(url.prettyURL(), mass, result,
                             _parser.elementsCount());
      }
      else
          errorMessage(errormsg);
      if (!url.isLocalFile())
          KIO::NetAccess::removeTempFile(tmpfile);
  }
}

void KMolCalcWidget::slotClear()
{
    /*
  //clear edit box
  _editFormula->clear();

  //clear output window
  _output->setText(QString::null);
    */
}

void KMolCalcWidget::writeConfig()
{
	KConfig* config = new KConfig("kmolcalcrc");

	config->sync();
	delete config;
}

void KMolCalcWidget::readConfig()
{
	KConfig* config = new KConfig("kmolcalcrc");

	delete config;
}


#include "kmolcalcwidget.moc"
