/* BEGIN software license
 *
 * msXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright(C) 2009,...,2018 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/>.
 *
 * END software license
 */


/////////////////////// Qt includes
#include <QtGlobal>


/////////////////////// Local includes
#include "Ionizable.hpp"
#include "PolChemDef.hpp"


namespace msxps
{

	namespace massxpert
	{



//! Constructs an Ionizable.
/*! The Ionizable instance will be an ionized entity if \p isIonized
    is true. The \p ponderable's mono and avg masses must thus be
    masses which take or do not take into account the data located
    in \p ionizeRule. If \p isIonized is true, the \p ionizeRule is
    validated and the level of the ionization must not be 0. If one
    of these two tests fails, this is an error and the program
    aborts.

  \param polChemDef Polymer chemistry definition(cannot be 0);

  \param name Name of \c this Ionizable(default to "NOT_SET");

  \param ponderable Ponderable(mono and avg masses);

  \param ionizeRule IonizeRule(defaults to IonizeRule(), that is
  an invalid IonizeRule).

  \param isIonized Indicates if the Ionizable to be constructed
  should be considered as an ionized chemical entity.
*/
Ionizable::Ionizable(const PolChemDef *polChemDef,
                     const QString &name,
                     const Ponderable &ponderable,
                     const IonizeRule &ionizeRule,
                     bool isIonized)
  : PolChemDefEntity(polChemDef, name),
    Ponderable(ponderable),
    m_ionizeRule(ionizeRule),
    m_isIonized(isIonized)
{
  if(m_isIonized)
    {
      // If the Ionizable is ionized, then that means that its
      // IonizeRule should validate and also that the ionization
      // level should not be 0.
      if(!m_ionizeRule.isValid() || m_ionizeRule.level() == 0)
        {
          qDebug() << __FILE__ << __LINE__ << "Failure to construct Ionizable";
          abort();
        }
    }
}


//! Constructs a copy of \p other.
/*! The Ionizable that is constructed in this manner will be
    identical to \p other. No assumption should be made as to the
    status of the created Ionizable. The caller should caracterize
    the ionization status of the Ionizable with isIonized().
 */
Ionizable::Ionizable(const Ionizable &other)
  : PolChemDefEntity(other),
    Ponderable(other),
    m_ionizeRule(other.m_ionizeRule),
    m_isIonized(other.m_isIonized)
{
}


//! Destroys \c this Ionizable.
Ionizable::~Ionizable()
{
}


//! Creates a new Ionizable.
/*! The newly created Ionizable is initialized using \c this.

  \return The newly created Ionizable, which should be deleted when
  no longer in use.
*/
Ionizable *
Ionizable::clone() const
{
  Ionizable *other = new Ionizable(*this);

  return other;
}


//! Modifies \p other to be identical to \p this.
/*!

  \param other Ionizable.
*/
void
Ionizable::clone(Ionizable *other) const
{
  Q_ASSERT(other);

  if(other == this)
    return;

  other->mp_polChemDef = mp_polChemDef;
  other->m_name        = m_name;

  other->m_mono = m_mono;
  other->m_avg  = m_avg;

  other->m_ionizeRule = m_ionizeRule;
  other->m_isIonized  = m_isIonized;
}


//! Modifies \p this to be identical to \p other.
/*!

  \param other Ionizable to be used as a mold.
*/
void
Ionizable::mold(const Ionizable &other)
{
  if(&other == this)
    return;

  mp_polChemDef = other.mp_polChemDef;
  m_name        = other.m_name;

  m_mono = other.m_mono;
  m_avg  = other.m_avg;

  m_ionizeRule = other.m_ionizeRule;
  m_isIonized  = other.m_isIonized;
}


//! Assigns \p other to \c this Ionizable.
/*!

  \param other Ionizable used as the mold to set values to \p this.

  \return A reference to \c this ionization rule.
*/
Ionizable &
Ionizable::operator=(const Ionizable &other)
{
  if(&other != this)
    mold(other);

  return *this;
}


//! Returns the IonizeRule as a constant reference.
/*!

  \return The IonizeRule as a constant reference.
*/
const IonizeRule &
Ionizable::ionizeRule() const
{
  return m_ionizeRule;
}


//! Returns the IonizeRule as a pointer.
/*!

  \return The IonizeRule as a pointer.
*/
IonizeRule *
Ionizable::ionizeRule()
{
  return &m_ionizeRule;
}


//! Returns the ionization status of \c this Ionizable.
/*! The ionization status is returned on the basis of the \c
    m_isIonized member boolean value.

  \return true if \c this Ionizable is ionized, false otherwise.
*/
bool
Ionizable::isIonized() const
{
  return m_isIonized;
}


//! Returns the ionization charge of \c this Ionizable.
/*! The charge is returned as a positive number(0 allowed) or as -1
    if the IonizeRule is not valid or if \c m_isIonized is false.

    \return the compound of the IonizeRule's \c m_charge with \c
    m_level if the IonizeRule is valid and \c m_isIonized is
    true. Else, -1 is returned.
*/
int
Ionizable::charge() const
{
  // If the member ionizeRule is not valid, then return -1, that is
  // inform the caller that something is not correct in the
  // "workflow".

  if(!m_ionizeRule.isValid())
    return -1;

  // Now, the ionizeRule is correct, but the ionizable does not
  // advertise that it has been ionized. In this case, its charge is
  // 0.

  if(!m_isIonized)
    return 0;

  // Finally, the ionizable is positively(in the logical sense)
  // ionized, that is its ionizeRule is valid and it advertises that
  // it is ionized, in which case we can return its charge.

  return (m_ionizeRule.charge() * m_ionizeRule.level());
}


//! Sets the charge of \c this Ionizable.
/*! The \p charge is set to this ionizable and if the setting is
  successful, the \c m_ionizeRule's level() * charge() compound is
  equal to the \p charge. The following logic is applied:

  \li If \c this ionizable is not ionized, then ionization occurs;

  \li If \c this ionizable is ionized, then deionize()'ation
  occurs prior to ionization with the new charge;

  \li Ionization can occur only if the the \c m_ionizeRule is
  valid;

  \return 1 if ionization went through correctly, 0 if nothing was
  performed but without error and -1 if an error occurred.
*/
int
Ionizable::setCharge(int charge)
{
  if(!m_ionizeRule.isValid())
    return -1;

  // If *this Ionizable is ionized, first deionize it with its own
  // m_ionizeRule, so that we get back to M, as we would say in
  // front of a mass spectrometer.

  if(m_isIonized)
    {
      if(!deionize())
        return -1;
      else
        // Make clear that at this point we are not ionized.
        m_isIonized = false;
    }

  // At this point, if charge is 0, then we are done, and we can
  // return a success.
  if(!charge)
    return 1;

  // At this point we can compute what IonizeRule's level should
  // be
  //(taking into account its charge, that is its unitary charge) so
  // that the total charge is identical to the parameter.

  int level = charge / m_ionizeRule.charge();

  m_ionizeRule.setLevel(level);

  if(ionize() == -1)
    return -1;

  // Return 1 because we know we changed something:
  return 1;
}


//! Ionizes \c this Ionizable.
/*! Ionization is performed on \c this Ionizable using the \c
  m_ionizeRule IonizeRule member of this Ionizable. The following
  logic is applied:

  \li If \c m_isIonized is true, that is, \c this Ionizable is
  ionize()'d already, then nothing is performed and 0 is returned
 (no error, no change);

  \li If \c m_ionizeRule is not valid, the ionize()ation fails,
   (nothing is changed and -1 is returned);

  \return 1 if ionization went through correctly, 0 if nothing was
  performed but without error and -1 if an error occurred.

  \sa ionize(const IonizeRule &ionizeRule)
*/
int
Ionizable::ionize()
{
  if(!m_ionizeRule.isValid())
    return -1;

  if(m_isIonized)
    return 0;

  // At this point perform the ionization proper.

  Formula formula(m_ionizeRule.formula());

  Ponderable temp(*this);

  // qDebug() << __FILE__ << __LINE__
  //          << "Before ionization:\n"
  //          << "Ionizable's charge / level:"
  //          << m_ionizeRule.charge() << "/" <<  m_ionizeRule.level()
  //          << " -- "
  //          << "Ionizable's whole charge:"
  //          << m_ionizeRule.charge() * m_ionizeRule.level()
  //          << " -- "
  //          << "Mono:" << temp.mono() << "Avg:" << temp.avg()
  //          << "\n\n";

  double localMono = 0;
  double localAvg  = 0;

  const QList<Atom *> &refList = mp_polChemDef->atomList();

  // Note the times(localIonizeRule.level()) param to call below.
  if(!formula.accountMasses(
       refList, &localMono, &localAvg, m_ionizeRule.level()))
    return -1;

  // OK, the accounting of the masses worked ok, we can update the
  // values in the mono and avg params(note that we know that the
  // charge and level values of m_ionizeRule cannot be <= 0 because
  // otherwise the m_ionizRule would not have validated.

  int ionCharge = m_ionizeRule.charge() * m_ionizeRule.level();

  m_mono += localMono;
  m_mono = m_mono / ionCharge;

  m_avg += localAvg;
  m_avg = m_avg / ionCharge;

  // Of course, we now are ionized.
  m_isIonized = true;

  // qDebug() << __FILE__ << __LINE__
  //          << "After ionization:\n"
  //          << "Ionizable's charge / level:"
  //          << m_ionizeRule.charge() << "/" <<  m_ionizeRule.level()
  //          << " -- "
  //          << "Ionizable's whole charge:"
  //          << m_ionizeRule.charge() * m_ionizeRule.level()
  //          << " -- "
  //          << "Mono:" << m_mono << "Avg:" << m_avg
  //          << "\n\n";

  // If something changed in the masses, then return 1, otherwise
  // return 0.
  if(temp != static_cast<Ponderable>(*this))
    {
      return 1;
    }

  return 0;
}


//! Ionizes \c this Ionizable.
/*! Ionization is performed on \c this Ionizable using the \p
    ionizeRule passed as parameter. The following checks are
    performed:

    \li If \p ionizeRule is not valid, nothing is performed and -1
    is returned;

    \li If \c m_isIonized is true, that is, \c this Ionizable is
    ionize()'d, then it is first deionize()'d. If deionize()'ation
    fails, nothing is changed and -1 is returned;

    When ionization is successfully performed with \p ionizeRule,
    then \c m_ionizeRule is set to be identical to \p ionizeRule and
    \c m_isIonized is set to true.

    \return -1 if an error was encountered; 0 if nothing was
    performed but without error; 1 if ionization was actually
    performed.
*/
int
Ionizable::ionize(const IonizeRule &ionizeRule)
{
  if(!ionizeRule.isValid())
    return -1;

  // If *this Ionizable is ionized, first deionize it with its own
  // m_ionizeRule, so that we get back to M, as we would say in
  // front of a mass spectrometer.

  Ponderable temp(*this);

  if(m_isIonized)
    {
      if(!deionize())
        return -1;
      else
        // Make clear that at this point we are not ionized.
        m_isIonized = false;
    }

  // At this point perform the ionization proper using 'ionizeRule'.

  Formula formula(ionizeRule.formula());

  double localMono = 0;
  double localAvg  = 0;

  const QList<Atom *> &refList = mp_polChemDef->atomList();

  // Note the times(ionizeRule.level()) param to call below.
  if(!formula.accountMasses(refList, &localMono, &localAvg, ionizeRule.level()))
    return -1;

  // OK, the accounting of the masses worked ok, we can update the
  // values in the mono and avg params(note that we know that the
  // charge and level values of ionizeRule cannot be <= 0 because
  // otherwise the ionizRule would not have validated.

  m_mono += localMono;
  m_avg += localAvg;

  // If the ionization rule is for actually ionizing, then perform
  // the division.
  if(ionizeRule.level())
    {
      m_mono = m_mono / (ionizeRule.charge() * ionizeRule.level());
      m_avg  = m_avg / (ionizeRule.charge() * ionizeRule.level());

      m_isIonized = true;
    }
  else
    {
      m_isIonized = false;
    }

  // Update the internal IonizeRule.
  m_ionizeRule = ionizeRule;

  //   qDebug() << __FILE__ << __LINE__
  // 	    << "After ionization: Mono:" << *mono << "Avg:" << avg;

  // If something changed in the masses, then return 1, otherwise
  // return 0.
  if(temp != *this)
    return 1;

  return 0;
}


//! Ionizes \p ionizable.
/*! Ionization is performed on \p onizable using the \p ionizeRule
    passed as parameter. The following checks are performed:

    \li If \p ionizeRule is not valid, nothing is performed and -1
    is returned;

    \li If \c m_isIonized is true, that is, \c this Ionizable is
    ionize()'d, then it is first deionize()'d. If deionize()'ation
    fails, nothing is changed and -1 is returned;

    When ionization is successfully performed with \p ionizeRule,
    then \c m_ionizeRule is set to be identical to \p ionizeRule and
    \c m_isIonized is set to true.

    \return -1 if an error was encountered; 0 if nothing was
    performed but without error; 1 if ionization was actually
    performed.
*/
int
Ionizable::ionize(Ionizable *ionizable,
                  const IonizeRule &ionizeRule)
{
  if(!ionizeRule.isValid())
    return -1;

  // If *this Ionizable is ionized, first deionize it with its own
  // m_ionizeRule, so that we get back to M, as we would say in
  // front of a mass spectrometer.

  if(ionizable->m_isIonized)
    {
      if(!ionizable->deionize())
        return -1;
      else
        // Make clear that at this point we are not ionized.
        ionizable->m_isIonized = false;
    }

  // At this point perform the ionization proper using 'ionizeRule'.

  Formula formula(ionizable->ionizeRule()->formula());

  Ponderable temp(*ionizable);

  double localMono = 0;
  double localAvg  = 0;

  const QList<Atom *> &refList =
    ionizable->polChemDef()->atomList();

  // Note the times(ionizeRule.level()) param to call below.
  if(!formula.accountMasses(refList, &localMono, &localAvg, ionizeRule.level()))
    return -1;

  // OK, the accounting of the masses worked ok, we can update the
  // values in the mono and avg params(note that we know that the
  // charge and level values of ionizeRule cannot be <= 0 because
  // otherwise the ionizRule would not have validated.

  ionizable->m_mono += localMono;
  ionizable->m_avg += localAvg;

  // If the ionization rule is for actually ionizing, then perform
  // the division.
  if(ionizeRule.level())
    {
      ionizable->m_mono =
        ionizable->m_mono / (ionizeRule.charge() * ionizeRule.level());

      ionizable->m_avg =
        ionizable->m_avg / (ionizeRule.charge() * ionizeRule.level());

      ionizable->m_isIonized = true;
    }
  else
    {
      ionizable->m_isIonized = false;
    }

  // Update the internal IonizeRule.
  ionizable->m_ionizeRule = ionizeRule;

  //   qDebug() << __FILE__ << __LINE__
  // 	    << "After ionization: Mono:" << *mono << "Avg:" << avg;

  // If something changed in the masses, then return 1, otherwise
  // return 0.
  if(temp != *ionizable)
    return 1;

  return 0;
}


//! Deionizes \c this Ionizable.
/*! This Ionizable is deionized using its member \c
    m_ionizeRule. The following logic is applied:

    \li If \c m_isIonized is false, that is \c this Ionizable is not
    ionized, then nothing is performed and 0 is returned(nothing
    done, but no error);

    \li If \c m_ionizeRule is not valid, then this is an error, as
    \c this Ionizable is ionized, and the IonizeRule is
    invalid. Return -1;

    \li If the deionization is performed successfully, \c
    m_isIonized is set to false.

  \return -1 if an error was encountered; 0 if nothing was performed
    but without error; 1 if deionization was actually performed.
*/
int
Ionizable::deionize()
{
  if(!m_isIonized)
    {
      // The Ionizable is not ionized, nothing to do, return true.
      return 0;
    }

  Ponderable temp(*this);

  // At this point we know the Ionizable is ionized, thus it is an
  // error that m_ionizeRule is not valid.

  if(!m_ionizeRule.isValid())
    return -1;

  // Now, reverse the usual M+zH/z(proteins) stuff.

  double localMono = m_mono * abs(m_ionizeRule.charge() * m_ionizeRule.level());

  double localAvg = m_avg * abs(m_ionizeRule.charge() * m_ionizeRule.level());

  Formula formula(m_ionizeRule.formula());

  const QList<Atom *> &refList = mp_polChemDef->atomList();

  // Note the negated 'times'(- m_ionizeRule.level())param to call
  // below so that we revert the chemical action that led level
  // times to the ionization of the analyte. Note that we do not
  // have any compound(level * charge) because we are dealing with
  // matter here, not charges, thus only 'level' is to be taken into
  // consideration.

  if(!formula.accountMasses(
       refList, &localMono, &localAvg, -m_ionizeRule.level()))
    return -1;

  // At this point we can update the member masses;

  m_mono = localMono;
  m_avg  = localAvg;

  m_isIonized = false;

  // If something changed in the masses, then return 1, otherwise
  // return 0.
  if(temp != *this)
    return 1;

  return 0;
}


double
Ionizable::molecularMass(MassType massType)
{
  Ionizable temp(*this);

  if(!temp.deionize())
    return -1;

  return temp.mass(massType);
}


bool
Ionizable::validate()
{
  int tests = 0;

  tests += PolChemDefEntity::validate();

  // If this Ionizable is ionized, then it is an error if the
  // m_ionizeRule is not valid !
  tests += (m_isIonized && m_ionizeRule.isValid());

  if(tests < 2)
    return false;

  return true;
}


bool
Ionizable::operator==(const Ionizable &other) const
{
  int tests = 0;

  tests += (m_mono == other.m_mono);
  tests += (m_avg == other.m_avg);
  tests += m_ionizeRule == other.m_ionizeRule;
  tests += m_isIonized == other.m_isIonized;

  if(tests < 4)
    return false;

  return true;
}


bool
Ionizable::operator!=(const Ionizable &other) const
{
  int tests = 0;

  tests += (m_mono != other.m_mono);
  tests += (m_avg != other.m_avg);
  tests += m_ionizeRule != other.m_ionizeRule;
  tests += m_isIonized != other.m_isIonized;

  if(tests > 0)
    return true;

  return false;
}


//! Calculates the masses of \c this Ionizable.
/*! The masses of the Ponderable are first calculated. If the
    returned value is true(which is always the case as of now), the
    following actions are taken:

    \li If m_isIonized is true, return true immediately, as nothing
    more needs to be done;

    \li If m_isIonized is false, \c this Ionizable is ionized() if
    and only if the m_ionizeRule is valid. If \c m_ionizeRule is not
    valid, false is returned.

    \return true if calculation succeeded, false otherwise.
    \sa ionize()
*/
bool
Ionizable::calculateMasses()
{
  if(!Ponderable::calculateMasses())
    return false;

  if(m_isIonized)
    {
      // Because the Ionizable is ionized, we have nothing more to
      // do.

      return true;
    }
  else
    {
      // The Ionizable is not ionized. If the IonizeRule is valid,
      // then we just ionize it.
      if(m_ionizeRule.isValid())
        {
          if(ionize() == -1)
            return false;
          else
            return true;
        }
    }

  // We should not be here.
  return false;
}

} // namespace massxpert

} // namespace msxps
