/**
 * \file /input/mascot/mimeparser.cpp
 * \date 17/2/2018
 * \author Olivier Langella
 * \brief basic mime multipart parser
 */

/*******************************************************************************
 * Copyright (c) 2018 Olivier Langella <olivier.langella@u-psud.fr>.
 *
 * This file is part of XTPcpp.
 *
 *     XTPcpp 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.
 *
 *     XTPcpp 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 XTPcpp.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contributors:
 *     Olivier Langella <olivier.langella@u-psud.fr> - initial API and
 *implementation
 ******************************************************************************/

#include "mimeparser.h"
#include <QRegExp>
#include <QDebug>
#include <pappsomspp/pappsoexception.h>

MimeParser::MimeParser(QIODevice *p_inputstream)
{
  _p_inputstream = p_inputstream;
}

MimeParser::~MimeParser()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  close();
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
}
bool
MimeParser::open()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  if(_p_inputstream->open(QIODevice::ReadOnly))
    {
      _real_in = new QTextStream(_p_inputstream);
    }
  else
    {
      throw pappso::PappsoException(
        QObject::tr("Error opening mime QIODevice"));
    }
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  return true;
}
bool
MimeParser::close()
{
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;

  _priv_file_string = "";
  if(_p_current_file_content != nullptr)
    {
      delete _p_current_file_content;
      _p_current_file_content = nullptr;
    }
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  if(_real_in != nullptr)
    {
      delete _real_in;
      _real_in = nullptr;
    }

  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  if(_p_inputstream != nullptr)
    {
      _p_inputstream->close();
      // delete _p_inputstream;
      _p_inputstream = nullptr;
    }
  qDebug() << __FILE__ << " " << __FUNCTION__ << " " << __LINE__;
  return true;
}
bool
MimeParser::goToFirstFile()
{
  qDebug() << "MimeParser::goToFirstFile begin";

  /*
  MIME-Version: 1.0 (Generated by Mascot version 1.0)
  Content-Type: multipart/mixed; boundary=gc0p4Jq0M2Yt08jU534c0p

  --gc0p4Jq0M2Yt08jU534c0p
  Content-Type: application/x-Mascot; name="parameters"
  */
  QRegExp regexp_boundary("^Content-Type:\\smultipart/mixed;\\sboundary=(.*)$");

  while(!_real_in->atEnd())
    {
      QString line = _real_in->readLine();
      qDebug() << "MimeParser::goToFirstFile line=" << line;
      if(regexp_boundary.exactMatch(line))
        {
          QStringList boundary_list = regexp_boundary.capturedTexts();
          _boundary                 = QString("--%1").arg(boundary_list[1]);
          break;
        }
    }

  if(_boundary.isEmpty())
    {
      qDebug() << "MimeParser::goToFirstFile _boundary.isEmpty";
      return false;
    }

  while(!_real_in->atEnd())
    {
      QString line = _real_in->readLine();
      if(line == _boundary)
        break;
    }
  qDebug() << "MimeParser::goToFirstFile end";
  return readFile();
}
bool
MimeParser::readFile()
{
  qDebug() << "MimeParser::readFile begin";
  _current_mime_type = "";
  _current_file_name = "";
  _priv_file_string  = "";

  if(_p_current_file_content != nullptr)
    {
      delete _p_current_file_content;
    }
  _p_current_file_content = new QTextStream(&_priv_file_string);

  QString line = _real_in->readLine();
  if(line.isEmpty())
    return false;
  // Content-Type: application/x-Mascot; name="masses"
  QRegExp regexp_mimetype("^Content-Type:\\s(.*);\\sname=\"(.*)\"$");
  if(regexp_mimetype.exactMatch(line))
    {
      QStringList mimetype_list = regexp_mimetype.capturedTexts();
      _current_mime_type        = mimetype_list[1];
      _current_file_name        = mimetype_list[2];
    }
  else
    {
      return false;
    }
  _real_in->readLine();
  while(!_real_in->atEnd())
    {
      QString line = _real_in->readLine();
      if(line == _boundary)
        break;
      *_p_current_file_content << line << endl;
    }
  qDebug() << "MimeParser::readFile end";
  return true;
}
bool
MimeParser::goToNextFile()
{
  return readFile();
}
const QString &
MimeParser::getCurrentMimeType() const
{
  return _current_mime_type;
}
const QString &
MimeParser::getCurrentFileName() const
{
  return _current_file_name;
}
QTextStream &
MimeParser::getCurrentTextStream()
{
  if(_p_current_file_content == nullptr)
    {
      throw pappso::PappsoException(
        QObject::tr("Error current file content empty"));
    }
  _p_current_file_content->reset();
  return *_p_current_file_content;
}
