/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2011 University of Bonn. 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 .
 */
/*
 * ExportGraph_ToJobs.cpp
 *
 *  Created on: 08.03.2012
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
// boost asio required before MemDebug due to placement new
#include 
#include "CodePatterns/MemDebug.hpp"
#include "Fragmentation/Exporters/ExportGraph_ToJobs.hpp"
#include 
#include "Box.hpp"
#include "Fragmentation/KeySet.hpp"
#include "Fragmentation/Automation/FragmentJobQueue.hpp"
#include "Fragmentation/Automation/MPQCFragmentController.hpp"
#include "Helpers/defs.hpp"
#include "Jobs/MPQCJob.hpp"
#include "LinearAlgebra/RealSpaceMatrix.hpp"
#include "Parser/FormatParserStorage.hpp"
#include "World.hpp"
ExportGraph_ToJobs::ExportGraph_ToJobs(
    const Graph &_graph,
    const enum HydrogenTreatment _treatment,
    const enum HydrogenSaturation _saturation) :
    ExportGraph(_graph, _treatment, _saturation),
    level(5)
{}
ExportGraph_ToJobs::~ExportGraph_ToJobs()
{}
void ExportGraph_ToJobs::operator()()
{
  std::vector jobs;
  KeySetsContainer KeySets;
  KeySetsContainer FullKeySets;
  jobs.reserve(TotalGraph.size());
  LOG(1, "INFO: Creating " << TotalGraph.size() << " possible bond fragmentation jobs.");
  // gather info about the domain
  double begin[NDIM] = { 0., 0., 0. };
  RealSpaceMatrix M = World::getInstance().getDomain().getM();
  M *= 1./AtomicLengthToAngstroem;  // scale to atomic length units
  const double size = M.at(0,0);
  double end[NDIM] = { size, size, size };
  const ParserTypes jobtype =
      FormatParserStorage::getInstance().getTypeFromName("mpqc");
  // go through all fragments, output to stream and create job therefrom
  ExportGraph::SaturatedFragment_ptr CurrentFragment = getNextFragment();
  for (; (CurrentFragment != NULL) && (CurrentFragment->getKeySet() != ExportGraph::EmptySet);
      CurrentFragment = getNextFragment()) {
    const KeySet &set = CurrentFragment->getKeySet();
    LOG(2, "INFO: Creating bond fragment job for set " << set << ".");
    // store config in stream
    {
      std::stringstream output;
      // save to stream
      CurrentFragment->OutputConfig(output, jobtype);
      // create job and insert
      FragmentJob::ptr testJob( new MPQCJob(JobId::IllegalJob, output.str(), begin, end, level) );
      jobs.push_back(testJob);
      // order is the same as the number of non-hydrogen atoms
      const KeySet &keyset = CurrentFragment->getKeySet();
      const size_t order = keyset.size();
      const KeySet &fullmolecule = CurrentFragment->getFullMolecule();
      const KeySet &saturationhydrogens = CurrentFragment->getSaturationHydrogens();
      KeySetsContainer::IntVector indices(keyset.begin(), keyset.end());
      KeySetsContainer::IntVector forceindices(fullmolecule.begin(), fullmolecule.end());
      {
        // replace all saturated hydrogen indices by "-1"
        for (KeySetsContainer::IntVector::iterator iter = forceindices.begin();
            iter != forceindices.end();
            ++iter)
          if (saturationhydrogens.find(*iter) != saturationhydrogens.end())
            *iter = -1;
      }
      KeySets.insert(indices, order);
      FullKeySets.insert(forceindices, order);
    }
    // store force index reference file
    // explicitly release fragment
    CurrentFragment.reset();
  }
  if (CurrentFragment == NULL) {
    ELOG(1, "Some error while obtaining the next fragment occured.");
    return;
  }
  // push final jobs
  FragmentJobQueue::getInstance().addJobs(jobs, KeySets, FullKeySets);
}