/* BEGIN software license
 *
 * MsXpertSuite - mass spectrometry software suite
 * -----------------------------------------------
 * Copyright (C) 2009--2024 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
 */


#include <QDebug>


#include "Averagine.hpp"


namespace MsXpS
{
namespace libXpertMass
{


Averagine::Averagine(IsotopicDataCstSPtr isotopic_data_csp)
  : mcsp_isotopicData(isotopic_data_csp)
{
  setupDefaultConfiguration();
}

Averagine::Averagine(const Averagine &other)
  : mcsp_isotopicData(other.mcsp_isotopicData),
    m_avg(other.m_avg),
    m_symbolContentMap(other.m_symbolContentMap)
{
}

Averagine::~Averagine()
{
}

Averagine &
Averagine::operator=(const Averagine &other)
{
  if(&other == this)
    return *this;

  mcsp_isotopicData  = other.mcsp_isotopicData;
  m_avg              = other.m_avg;
  m_symbolContentMap = other.m_symbolContentMap;

  return *this;
}

void
Averagine::setIsotopicData(IsotopicDataCstSPtr isotopic_data_csp)
{

  assert(isotopic_data_csp != nullptr && isotopic_data_csp.get() != nullptr);

  mcsp_isotopicData = isotopic_data_csp;

  if(!validate())
    qFatal("The Averagine validation failed after setting new isotopic data.");

  computeAvgMass();
}

void
Averagine::setContent(QString &symbol, double content)
{
  m_symbolContentMap[symbol] = content;

  if(!validate())
    qFatal("The Averagine validation failed after setting new symbol content.");

  computeAvgMass();
}

double
Averagine::getContent(QString &symbol) const
{
  auto iter = m_symbolContentMap.find(symbol);
  assert(iter != m_symbolContentMap.end());

  return iter->second;
}

void
Averagine::setFormula(const QString formula_string)
{
  Formula formula(formula_string);

  // The formula is asked to validate with storage of the found symbol/count
  // pairs and with resetting of the previous contents of the symbol/count map.
  if(!formula.validate(mcsp_isotopicData, true, true))
    qFatal("The formula passed as argument did not validate.");

  m_formula = formula;
}

double
Averagine::getAvgMass() const
{
  return m_avg;
}

double
Averagine::computeFormulaAveragineEquivalents(const QString &formula_string)
{
  // If something is wrong, qFatal().
  if(!formula_string.isEmpty())
    setFormula(formula_string);

  // At this point, we do have m_formula fine and that has been validated.

  double formula_average_mass = 0;
  m_formula.accountMasses(mcsp_isotopicData, &formula_average_mass);

  // There are many checks in the code that m_avg is not 0.
  double averagine_equivs = formula_average_mass / m_avg;

  return averagine_equivs;
}


double
Averagine::computeFormulaMonoMass(const QString &formula_string)
{
  // If something is wrong, qFatal().
  double averagine_equivs = computeFormulaAveragineEquivalents(formula_string);

  double mono_mass = 0;

  for(std::pair<QString, double> pair : m_symbolContentMap)
    {
      bool ok = false;
      mono_mass += mcsp_isotopicData->getMonoMassBySymbol(pair.first, &ok) *
                   averagine_equivs;

      if(!ok)
        qFatal("Failed to get mono mass for symbol.");
    }

  return mono_mass;
}

bool
Averagine::validate()
{
  if(!m_avg)
    qFatal("It is not possible that m_avg of Averagine be 0.");

  for(std::pair<QString, double> pair : m_symbolContentMap)
    {
      if(!mcsp_isotopicData->containsSymbol(pair.first))
        return false;
    }

  return true;
}


void
Averagine::setupDefaultConfiguration()
{
  m_symbolContentMap["C"] = 4.9384;
  m_symbolContentMap["H"] = 7.7583;
  m_symbolContentMap["N"] = 1.3577;
  m_symbolContentMap["O"] = 1.4773;
  m_symbolContentMap["S"] = 0.0417;

  computeAvgMass();
}


double
Averagine::computeAvgMass()
{

  for(std::pair<QString, double> pair : m_symbolContentMap)
    {
      bool ok = false;
      m_avg +=
        mcsp_isotopicData->getAvgMassBySymbol(pair.first, &ok) * pair.second;

      if(!ok)
        qFatal("Failed to get mono mass for symbol.");
    }

  if(!m_avg)
    qFatal("It is not possible that m_avg of Averagine be 0.");

  return m_avg;
}


} // namespace libXpertMass

} // namespace MsXpS
