/* 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 "MassDataServerThread.hpp"


namespace MsXpS
{
namespace libXpertMass
{

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

\brief The MassDataServerThread class provides a server in a QThread instance.
*/


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

\brief The data to be served.
*/

/*!
\variable MsXpS::libXpertMass::MassDataServerThread::m_socketDescriptor

\brief The socket descriptor of the connection.
*/

/*!
\variable MsXpS::libXpertMass::MassDataServerThread::mpa_tcpSocket

\brief The socket to be used for the connection.
*/


/*!
\brief Constructs a MassDataServerThread instance.

\list
\li \a socket_descriptor: the socket descriptor of the connection to the
client.
\li \a data: the data to be served.
\li \a parent: the parent QObject.
\endlist
*/
MassDataServerThread::MassDataServerThread(qintptr socket_descriptor,
                                           const QByteArray &data,
                                           QObject *parent)
  : QThread(parent), m_socketDescriptor(socket_descriptor), m_data(data)
{
  // qDebug() << "Constructing the server thread with data of size:"
  //<< m_data.size() << this;
}

/*!
\brief Destructs this MassDataServerThread instance.

Deletes mpa_tcpSocket if non-nullptr.
*/
MassDataServerThread::~MassDataServerThread()
{
  if(mpa_tcpSocket != nullptr)
    {
      qDebug("Now deleting the socket.");
      delete mpa_tcpSocket;
    }
}

/*!
\brief Runs the task in this thread.

Allocates a new QTcpSocket and sets the \c m_socketDescriptor. If the member
m_data are not empty, writes the data to the socket and disconnects.
*/
void
MassDataServerThread::run()
{
  // qDebug() << "The server thread has been run at"
  //<< QDateTime::currentDateTime();

  mpa_tcpSocket = new QTcpSocket();

  if(!mpa_tcpSocket->setSocketDescriptor(m_socketDescriptor))
    {
      qDebug() << "There was an error initializing the socket descriptor.";

      emit errorSignal(mpa_tcpSocket->error());
      return;
    }

  if(m_data.size())
    {
      QByteArray byte_array;
      QDataStream out_stream(&byte_array, QIODevice::WriteOnly);
      out_stream.setVersion(QDataStream::Qt_5_0);
      out_stream << m_data;

      // qDebug() << "On the verge of writing byte_array of size:"
      //<< byte_array.size();

      int written_bytes = mpa_tcpSocket->write(byte_array);

      // qDebug() << "Now written " << written_bytes << " bytes to the socket
      // at"
      //<< QDateTime::currentDateTime();

      if(written_bytes >= byte_array.size())
        {
          // qDebug() << "The data could be written fine. Clearing them now.";

          emit writtenDataSignal(written_bytes);

          m_data.clear();
        }
      // else
      // qDebug() << "The data could not be written fully, not sending "
      //"successful process signal.";
    }
  // else
  // qDebug() << "There are no data to be written to the socket at"
  //<< QDateTime::currentDateTime();

  qDebug() << "Now trying to disconnect from host.";
  mpa_tcpSocket->disconnectFromHost();
  if (mpa_tcpSocket->state() == QAbstractSocket::UnconnectedState
  || mpa_tcpSocket->waitForDisconnected(1000)) {
    qDebug("Succesfully disconnected from the host!");
  }
}

} // namespace libXpertMass

} // namespace MsXpS
