/*
 * 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 .
 */
/*
 * ForceAnnealingAction.cpp
 *
 *  Created on: Aug 02, 2014
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "CodePatterns/MemDebug.hpp"
#include "Actions/UndoRedoHelpers.hpp"
#include "Atom/atom.hpp"
#include "Atom/AtomicInfo.hpp"
#include "Atom/AtomSet.hpp"
#include "CodePatterns/Log.hpp"
#include "CodePatterns/Verbose.hpp"
#include "Dynamics/ForceAnnealing.hpp"
#include "molecule.hpp"
#include "World.hpp"
#include "WorldTime.hpp"
#include 
#include 
#include 
#include 
#include "Actions/MoleculeAction/ForceAnnealingAction.hpp"
using namespace MoleCuilder;
enum VectorIndexType {
  PositionIndex=0,
  VelocityIndex=1,
  ForceIndex=2
};
// and construct the stuff
#include "ForceAnnealingAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr MoleculeForceAnnealingAction::performCall() {
  AtomSetMixin > set(World::getInstance().getSelectedAtoms());
  if (set.empty()) {
    STATUS("No atoms selected.");
    return Action::failure;
  }
  // we always operate relative to current time step, except on single debug output
  size_t CurrentStep = WorldTime::getInstance().getTime();
  if (params.DoOutput.get()) {
    // copy current time step to new one and and proceed on this one
    for (World::AtomSelectionIterator iter = World::getInstance().beginAtomSelection();
        iter != World::getInstance().endAtomSelection();
        ++iter) {
      atom * const Walker = iter->second;
      Walker->setPositionAtStep(CurrentStep+1,
          Walker->getPositionAtStep(CurrentStep));
      Walker->setAtomicVelocityAtStep(CurrentStep+1,
          Walker->getAtomicVelocityAtStep(CurrentStep));
      Walker->setAtomicForceAtStep(CurrentStep+1,
          Walker->getAtomicForceAtStep(CurrentStep));
    }
    // increment to next time step: re-creates bond graph
    ++CurrentStep;
    World::getInstance().setTime(CurrentStep);
  }
  ForceAnnealing > optimizer(
      set,
      params.Deltat.get(),
      true,
      params.steps.get());
  // parse forces into next step
  if (!params.forcesfile.get().string().empty()) {
    LOG(1, "Parsing forces file.");
    if (!optimizer.parseForcesFile(params.forcesfile.get().string().c_str(), CurrentStep))
      LOG(2, "File " << params.forcesfile.get() << " not found.");
    else
      LOG(2, "File " << params.forcesfile.get() << " found and parsed.");
  }
  // create undo state for all selected atoms (undo info)
  std::vector UndoInfo;
  UndoInfo.reserve(set.size());
  {
    for (World::AtomSelectionConstIterator iter = World::getInstance().beginAtomSelection();
        iter != World::getInstance().endAtomSelection();
        ++iter)
      UndoInfo.push_back(AtomicInfo(*(iter->second)));
  }
  // perform optimization step
  LOG(1, "Structural optimization.");
  optimizer(CurrentStep, 1);
  STATUS("Successfully optimized structure by one step.");
//  // increment to next time step
//  World::getInstance().setTime(CurrentStep+1);
  std::vector RedoInfo;
  RedoInfo.reserve(set.size());
  {
    for (World::AtomSelectionConstIterator iter = World::getInstance().beginAtomSelection();
        iter != World::getInstance().endAtomSelection();
        ++iter)
      RedoInfo.push_back(AtomicInfo(*(iter->second)));
  }
  MoleculeForceAnnealingState *UndoState =
    new MoleculeForceAnnealingState(UndoInfo, RedoInfo, params);
  return ActionState::ptr(UndoState);
}
ActionState::ptr MoleculeForceAnnealingAction::performUndo(ActionState::ptr _state) {
  MoleculeForceAnnealingState *state =
      assert_cast(_state.get());
  // set stored old state
  SetAtomsFromAtomicInfo(state->UndoInfo);
  return ActionState::ptr(_state);
}
ActionState::ptr MoleculeForceAnnealingAction::performRedo(ActionState::ptr _state){
  MoleculeForceAnnealingState *state =
      assert_cast(_state.get());
  // set stored new state
  SetAtomsFromAtomicInfo(state->RedoInfo);
  return ActionState::ptr(_state);
}
bool MoleculeForceAnnealingAction::canUndo() {
  return true;
}
bool MoleculeForceAnnealingAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */