/**
 * \file pappsomspp/processing/tandemwrapper/wraptandemresults.cpp
 * \date 13/11/2021
 * \author Olivier Langella
 * \brief rewrites tandem xml output file with temporary files
 */

/*******************************************************************************
 * Copyright (c) 2021 Olivier Langella <Olivier.Langella@u-psud.fr>.
 *
 * This file is part of PAPPSOms-tools.
 *
 *     PAPPSOms-tools 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 3 of the License, or
 *     (at your option) any later version.
 *
 *     PAPPSOms-tools 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 PAPPSOms-tools.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include "wraptandemresults.h"
#include <QFileInfo>
#include "../../pappsoexception.h"


namespace pappso
{

WrapTandemResults::WrapTandemResults(const QString &final_tandem_output,
                                     const QString &original_msdata_file_name)
  : m_destinationTandemOutputFile(final_tandem_output)
{
  qDebug() << final_tandem_output;
  m_originalMsDataFileName =
    QFileInfo(original_msdata_file_name).absoluteFilePath();
  if(!m_destinationTandemOutputFile.open(QIODevice::WriteOnly))
    {
      throw pappso::PappsoException(
        QObject::tr("ERROR: unable to open %1 to write XML output")
          .arg(final_tandem_output));
    }
  m_writerXmlTandemOutput.setDevice(&m_destinationTandemOutputFile);
  m_writerXmlTandemOutput.writeStartDocument("1.0");
  m_writerXmlTandemOutput.setAutoFormatting(true);
}

WrapTandemResults::~WrapTandemResults()
{
}

void
WrapTandemResults::setInputParameters(const QString &label_name_attribute,
                                      const QString &input_value)
{
  m_mapTandemInputParameters.insert(
    std::pair<QString, QString>(label_name_attribute, input_value));
}

void
WrapTandemResults::process_group_note()
{
  cloneStartElement(m_writerXmlTandemOutput);
  while(m_qxmlStreamReader.readNext() && !m_qxmlStreamReader.isEndElement())
    {
      if(m_qxmlStreamReader.isStartElement())
        {
          QString type =
            m_qxmlStreamReader.attributes().value("type").toString();
          QString label =
            m_qxmlStreamReader.attributes().value("label").toString();
          qDebug() << "type=" << type << " label=" << label;
          //    qDebug() << "XtandemParamSaxHandler::endElement_note begin " <<
          //   <note type="input" label="spectrum,
          //   path">/tmp/tandemwrapper-IehrEL/msdata.mzxml</note>

          if(label == "spectrum, path")
            {
              //<note type="input"
              // label="spectrum,path">/gorgone/pappso/jouy/raw/2019_Lumos/20191222_107_Juste/20191222_18_EF1.mzXML</note>
              // m_originMzDataFileName = m_currentText;
              // p_writeXmlTandemOutput->writeCharacters(m_destinationMzXmlFileName);

              m_writerXmlTandemOutput.writeStartElement("note");
              m_writerXmlTandemOutput.writeAttributes(
                m_qxmlStreamReader.attributes());
              m_writerXmlTandemOutput.writeCharacters(m_originalMsDataFileName);
              m_writerXmlTandemOutput.writeEndElement();


              for(auto pair_input : m_mapTandemInputParameters)
                {
                  m_writerXmlTandemOutput.writeStartElement("note");
                  m_writerXmlTandemOutput.writeAttribute("type", "input");
                  m_writerXmlTandemOutput.writeAttribute("label",
                                                         pair_input.first);
                  m_writerXmlTandemOutput.writeCharacters(pair_input.second);

                  m_writerXmlTandemOutput.writeEndElement();
                }
              m_qxmlStreamReader.skipCurrentElement();
            }
          else if(label == "output, path")
            {

              //<note type="input" label="output,
              // path">/tmp/tandemwrapper-sSGxtE/output_tandem.xml</note>

              m_writerXmlTandemOutput.writeStartElement("note");
              m_writerXmlTandemOutput.writeAttributes(
                m_qxmlStreamReader.attributes());
              m_writerXmlTandemOutput.writeCharacters(
                QFileInfo(m_destinationTandemOutputFile).absoluteFilePath());
              m_writerXmlTandemOutput.writeEndElement();
              m_qxmlStreamReader.skipCurrentElement();
            }
          else
            {
              cloneElement(m_writerXmlTandemOutput);
            }
        }
    }
  m_writerXmlTandemOutput.writeEndElement();
}

void
WrapTandemResults::readStream()
{
  qDebug();
  if(m_qxmlStreamReader.readNextStartElement())
    {
      if(m_qxmlStreamReader.name().toString() == "bioml")
        {
          cloneStartElement(m_writerXmlTandemOutput);
          qDebug();
          while(m_qxmlStreamReader.readNextStartElement())
            {
              if(m_qxmlStreamReader.name().toString() == "group")
                {
                  QString type =
                    m_qxmlStreamReader.attributes().value("type").toString();
                  if(type == "model")
                    {
                      cloneElement(m_writerXmlTandemOutput);
                    }
                  else if(type == "parameters")
                    {
                      QString label = m_qxmlStreamReader.attributes()
                                        .value("label")
                                        .toString();
                      if(label == "performance parameters")
                        {
                          cloneElement(m_writerXmlTandemOutput);
                        }
                      else if(label == "input parameters")
                        {
                          process_group_note();
                          // cloneElement(m_writerXmlTandemOutput);
                        }
                      else if(label == "unused input parameters")
                        {
                          cloneElement(m_writerXmlTandemOutput);
                        }
                      else
                        {
                          m_qxmlStreamReader.skipCurrentElement();
                        }
                    }
                }
              else
                {
                  qDebug() << m_qxmlStreamReader.name();
                  // read_note();
                  cloneStartElement(m_writerXmlTandemOutput);


                  m_writerXmlTandemOutput.writeCharacters(
                    m_qxmlStreamReader.readElementText());

                  m_writerXmlTandemOutput.writeEndElement();
                }
            }
        }
      else
        {
          m_qxmlStreamReader.raiseError(
            QObject::tr("Not an X!Tandem result file"));
          m_qxmlStreamReader.skipCurrentElement();
        }
    }
  m_writerXmlTandemOutput.writeEndDocument();
  m_destinationTandemOutputFile.close();
  qDebug();
}

} // namespace pappso
