/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2014 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 .
 */
/*
 * MPQCCommandFragmentController.cpp
 *
 *  Created on: Apr 14, 2014
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include 
// boost asio needs specific operator new
//#include 
#include "CodePatterns/MemDebug.hpp"
#include "MPQCCommandFragmentController.hpp"
#include 
#include 
#include 
#include "CodePatterns/Assert.hpp"
#include "CodePatterns/Log.hpp"
#include "Box.hpp"
#include "Helpers/defs.hpp"
#include "Fragmentation/Automation/FragmentJobQueue.hpp"
#include "Jobs/MPQCCommandJob.hpp"
#include "LinearAlgebra/RealSpaceMatrix.hpp"
#include "World.hpp"
// static entities
unsigned int MPQCCommandFragmentController::nextid = 0;
bool MPQCCommandFragmentController::addJobsFromQueue(
    const MPQCData::DoLongrange_t _DoLongrange,
    const MPQCData::DoValenceOnly_t _DoValenceOnly,
    const std::string &_executable
    )
{
  // give them all valid ids
  std::vector newjobs = FragmentJobQueue::getInstance().getJobs();
  for (std::vector::iterator jobiter = newjobs.begin();
      jobiter != newjobs.end();
      ++jobiter) {
    MPQCCommandJob *job = boost::polymorphic_downcast(jobiter->get());
//    job->DoLongrange = _DoLongrange;
//    job->DoValenceOnly = _DoValenceOnly;
#ifndef HAVE_JOBMARKET
    JobId_t id = getAvailableId();
    if (id == (JobId_t)JobId::IllegalJob) {
      queue.clear();
      break;
    }
    job->setId(id);
    if (!_executable.empty())
      job->setCommand(_executable);
    job->setSuffix(".in");
#endif /* cause we don't inherit from FragmentController */
    // add the jobs
    queue.push_back(job);
  }
  return queue.size();
}
void MPQCCommandFragmentController::run()
{
  const size_t NoExpectedResults = queue.size();
  // take jobs from queue and add them
  std::vector resultvector;
  while(!queue.empty()) {
    // pop job from list
    MPQCCommandJob *job = queue.front();
    queue.pop_front();
    // run job and set exitflag if failed (>0)
    FragmentResult::ptr result = job->Work();
    if (result->exitflag) {
      ELOG(2, "Job #" << job->getId() << " has failed execution.");
    }
    exitflag = result->exitflag == 0 ?
        exitflag :
        ( result->exitflag > exitflag ?
            result->exitflag :
            exitflag );
    // store result
    resultvector.push_back(result);
    handler(resultvector.size(), NoExpectedResults);
  }
  // convert all results to MPQCData
  std::vector fragmentData;
  results.ConvertFragmentResultTo(resultvector, fragmentData);
  // insert into final map
  results.insertResults(resultvector, fragmentData);
}