/* BEGIN software license
 *
 * MsXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright (C) 2009--2020 Filippo Rusconi
 *
 * http://www.msxpertsuite.org
 *
 * This file is part of the MsXpertSuite project.
 *
 * The MsXpertSuite project is the successor of the massXpert project. This
 * project now includes various independent modules:
 *
 * - massXpert, model polymer chemistries and simulate mass spectrometric data;
 * - mineXpert, a powerful TIC chromatogram/mass spectrum viewer/miner;
 *
 * This program 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.
 *
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * *****************************************************************************
 * This specific code is a port to C++ of the Envemind Python code by Radzinski
 * and colleagues of IsoSpec fame (Lacki, Startek and company :-)
 *
 * See https://github.com/PiotrRadzinski/envemind.
 * *****************************************************************************
 *
 * END software license
 */


#include <QDebug>
#include <QDateTime>

#include "MassDataServer.hpp"
#include "MassDataServerThread.hpp"


namespace MsXpS
{
namespace libXpertMass
{


/*!
\class MsXpS::libXpertMass::MassDataServer
\inmodule libXpertMass
\ingroup XpertMassUtilities
\inheaderfile MassDataServer.hpp

\brief The MassDataServer class provides a network server.
*/

/*!
\variable MsXpS::libXpertMass::MassDataServer::m_data

\brief The data to be served.
*/

/*!
\brief Constructs a MassDataServer instance.

\list
\li \a parent: QObject parent.
\endlist
*/
MassDataServer::MassDataServer(QObject *parent) : QTcpServer(parent)
{
}

/*!
\brief Destructs this MassDataServer instance.
*/
MassDataServer::~MassDataServer()
{
}

/*!
\brief Sets to this MassDataServer instance the data to be served in
\a byte_array.
*/
void
MassDataServer::serveData(const QByteArray &byte_array)
{
  m_data = byte_array;

  // qDebug() << "Stored the byte array to be served upon connection. Size:"
  //<< m_data.size();
}

/*!
\brief Handles an incoming connection with socket descriptor \a
socket_descriptor.

If the member m_data are not empty, allocates a MassDataServerThread to serve
these data.
*/
void
MassDataServer::incomingConnection(qintptr socket_descriptor)
{
  if(!m_data.size())
    {
      qDebug()
        << "In this incoming connection we have no data to serve. Returning at:"
        << QDateTime::currentDateTime().toString();

      // It is not because we have not data to use as a response to the caller
      // that we do not perform the connection closing stuff! Otherwise we
      // consume a file descriptor (the socket) each time a connection is tried
      // here from the client.... Bug that has broken my head for weeks...
      QTcpSocket tcpSocket;

      if(!tcpSocket.setSocketDescriptor(socket_descriptor))
        return;

      tcpSocket.disconnectFromHost();
      tcpSocket.waitForDisconnected();

      return;
    }

  qDebug() << "In this incoming connection, the data to serve have size:"
           << m_data.size() << "at:" << QDateTime::currentDateTime().toString();

  MassDataServerThread *mass_data_server_thread_p =
    new MassDataServerThread(socket_descriptor, m_data, this);

  connect(mass_data_server_thread_p,
          &MassDataServerThread::finished,
          mass_data_server_thread_p,
          &MassDataServerThread::deleteLater);

  connect(mass_data_server_thread_p,
          &MassDataServerThread::errorSignal,
          this,
          &MassDataServer::error);

  connect(
    mass_data_server_thread_p,
    &MassDataServerThread::writtenDataSignal,
    [this](std::size_t written_bytes) {
      qDebug() << "The data were written by the thread-based server socket "
                  "with written_bytes:"
               << written_bytes << ". Clearing the data now.";
      m_data = "";
    });

  mass_data_server_thread_p->start();
}

/*!
\brief Reports the \a socket_error to the console using qDebug().
*/
void
MassDataServer::error(QTcpSocket::SocketError socket_error)
{
  qDebug() << "An error occurred in the thread:" << socket_error;
}


} // namespace libXpertMass

} // namespace MsXpS
