/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2012 University of Bonn. All rights reserved.
 * Copyright (C)  2013 Frederik Heber. All rights reserved.
 * 
 *
 *   This file is part of MoleCuilder.
 *
 *    MoleCuilder 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 2 of the License, or
 *    (at your option) any later version.
 *
 *    MoleCuilder 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 MoleCuilder.  If not, see .
 */
/*
 * VMGFragmentController.cpp
 *
 *  Created on: Aug 27, 2012
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
// boost asio needs specific operator new
#include 
#include "CodePatterns/MemDebug.hpp"
#include "VMGFragmentController.hpp"
#include "Atom/atom.hpp"
#include "Element/element.hpp"
#include "Helpers/defs.hpp"
#include "Jobs/VMGJob.hpp"
#include "molecule.hpp"
#include "World.hpp"
/** Helper function for the number of core electrons of a given element \a z.
 *
 * \param z atomic number of element
 * \return number of core electrons for this element
 */
static int getCoreElectrons(const int z)
{
  int n=0;
  if (z > 2) n += 2;
  if (z > 10) n += 8;
  if (z > 18) n += 8;
  if (z > 30) n += 10;
  if (z > 36) n += 8;
  if (z > 48) n += 10;
  if (z > 54) n += 8;
  return n;
}
bool VMGFragmentController::createLongRangeJobs(
    const std::map &fragmentData,
    const std::vector &full_sampled_grid,
    const size_t near_field_cells,
    const size_t interpolation_degree,
    const SampleParticles_t _SampleParticles,
    const TreatGrid_t _TreatGrid,
    const MPQCData::DoValenceOnly_t _DoValenceOnly,
    const bool _DoPrintDebug,
    const bool _OpenBoundaryConditions,
    const bool _DoSmearCharges)
{
  std::vector jobs;
  /// add one job for each fragment as the short-range correction which we need
  /// to subtract from the obtained full potential to get the long-range part only
  for (std::map::const_iterator iter = fragmentData.begin();
      iter != fragmentData.end(); ++iter) {
    const JobId_t next_id = getAvailableId();
    const MPQCData &data = iter->second;
    LOG(1, "INFO: Creating VMGJob with " << data.sampled_grid
        << " gridpoints and " << data.charges.size() << " particle charges.");
    FragmentJob::ptr testJob(
        new VMGJob(
            next_id,
            _TreatGrid == DoTreatGrid ?
                data.sampled_grid :
                SamplingGrid(data.sampled_grid.begin, data.sampled_grid.end, data.sampled_grid.level),
            data.positions,
            data.charges,
            near_field_cells,
            interpolation_degree,
            _SampleParticles == DoSampleParticles,
            _DoPrintDebug,
            _OpenBoundaryConditions,
            _DoSmearCharges) );
    jobs.push_back(testJob);
  }
  /// prepare positions and charges of full system
  /// \note we cannot use the summed up Fragment here, as the saturation hydrogens
  /// are in the way and cannot be sorted out properly/in a simple fashion.
  std::vector< std::vector > positions;
  std::vector charges;
  {
    const World::ConstAtomComposite &atoms = const_cast(World::getInstance()).
        getAllAtoms();
    positions.reserve(atoms.size());
    charges.reserve(atoms.size());
    std::vector position(3, 0.);
    for (World::ConstAtomComposite::const_iterator iter = atoms.begin();
        iter != atoms.end(); ++iter) {
      const Vector &pos = (*iter)->getPosition();
      // convert positions to atomic length units
      for (size_t i=0;i<3;++i) position[i] = pos[i]/AtomicLengthToAngstroem;
      positions.push_back(position);
      int charge = (*iter)->getElement().getAtomicNumber();
      // subtract core electron charge from nuclei charge if only valence sampled
      if (_DoValenceOnly == MPQCData::DoSampleValenceOnly)
        charge -= getCoreElectrons(charge);
      charges.push_back((double)charge);
    }
  }
  /// and submit full job
  for(std::vector::const_iterator iter = full_sampled_grid.begin();
      iter != full_sampled_grid.end();
      ++iter) {
    const SamplingGrid &grid = *iter;
    const JobId_t next_id = getAvailableId();
    LOG(1, "INFO: Creating full VMGJob with " << *iter
        << " gridpoints and " << charges.size() << " particle charges.");
    FragmentJob::ptr testJob(
        new VMGJob(
            next_id,
            _TreatGrid == DoTreatGrid ?
                grid :
                SamplingGrid(grid.begin, grid.end, grid.level),
            positions,
            charges,
            near_field_cells,
            interpolation_degree,
            _SampleParticles == DoSampleParticles,
            _DoPrintDebug,
            _OpenBoundaryConditions,
            _DoSmearCharges) );
    jobs.push_back(testJob);
  }
  /// then send jobs to controller
  addJobs(jobs);
  sendJobs(host, port);
  RunService("Adding VMGJobs");
  return true;
}