/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2010-2012 University of Bonn. All rights reserved.
 * Copyright (C)  2013-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 .
 */
/*
 * VerletIntegrationAction.cpp
 *
 *  Created on: May 10, 2010
 *      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/VerletForceIntegration.hpp"
#include "molecule.hpp"
#include "World.hpp"
#include "WorldTime.hpp"
#include 
#include 
#include 
#include 
#include "Actions/MoleculeAction/VerletIntegrationAction.hpp"
using namespace MoleCuilder;
enum VectorIndexType {
  PositionIndex=0,
  VelocityIndex=1,
  ForceIndex=2,
  MAXINDEX
};
// and construct the stuff
#include "VerletIntegrationAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr MoleculeVerletIntegrationAction::performCall() {
  AtomSetMixin > set(World::getInstance().getSelectedAtoms());
  if (set.empty()) {
    LOG(0, "STATUS: No atoms selected.");
    return Action::failure;
  }
  // we always operate relative to current time step
  const size_t CurrentStep = WorldTime::getInstance().getTime();
  VerletForceIntegration > Verlet(set, params.Deltat.get(), true);
  // parse forces into next step
  if (!params.forcesfile.get().string().empty()) {
    LOG(1, "Parsing forces file.");
    if (!Verlet.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 velocity verlet update
  Verlet(CurrentStep+1, 1, 0, params.FixedCenterOfMass.get());
  LOG(0, "STATUS: Successfully performed updates on velocity and position.");
  // increment to next time step: re-creates bond graph
  World::getInstance().setTime(CurrentStep+1);
  // create undo state for all selected atoms (redo info):
  // we need:
  // -# forces from last step (possible parsing forces file, already in UndoInfo)
  // -# velocities from last step (..UpdateU(), already in UndoInfo)
  // -# current position (..UpdateX())
  std::vector UpdatedStep(MAXINDEX);
  UpdatedStep[PositionIndex].reserve(set.size());
  UpdatedStep[VelocityIndex].reserve(set.size());
  UpdatedStep[ForceIndex].reserve(set.size());
  {
    for (World::AtomSelectionConstIterator iter = World::getInstance().beginAtomSelection();
        iter != World::getInstance().endAtomSelection();
        ++iter) {
      UpdatedStep[PositionIndex].push_back(iter->second->getPositionAtStep(CurrentStep+1));
      UpdatedStep[VelocityIndex].push_back(iter->second->getAtomicVelocityAtStep(CurrentStep));
      UpdatedStep[ForceIndex].push_back(iter->second->getAtomicForceAtStep(CurrentStep));
    }
  }
  MoleculeVerletIntegrationState *UndoState =
      new MoleculeVerletIntegrationState(UndoInfo, UpdatedStep, params);
  return ActionState::ptr(UndoState);
}
ActionState::ptr MoleculeVerletIntegrationAction::performUndo(ActionState::ptr _state) {
  MoleculeVerletIntegrationState *state =
      assert_cast(_state.get());
  // go back one step
  const size_t CurrentStep = WorldTime::getInstance().getTime();
  World::getInstance().setTime(CurrentStep-1);
  // remove current step for all modified atoms
  removeLastStep(getIdsFromAtomicInfo(state->UndoInfo), CurrentStep);
  // and set back the old step (forces have been changed)
  SetAtomsFromAtomicInfo(state->UndoInfo);
  return ActionState::ptr(_state);
}
ActionState::ptr MoleculeVerletIntegrationAction::performRedo(ActionState::ptr _state){
  MoleculeVerletIntegrationState *state =
      assert_cast(_state.get());
  // set forces and velocities
  ResetAtomVelocity(state->UndoInfo, state->UpdatedStep[VelocityIndex]);
  ResetAtomForce(state->UndoInfo, state->UpdatedStep[ForceIndex]);
  // set stored new state
  size_t CurrentStep = WorldTime::getInstance().getTime()+1;
  addNewStep(state->UndoInfo, CurrentStep);
  // add a new time step
  World::getInstance().setTime(CurrentStep);
  // and set positions of the new step
  ResetAtomPosition(state->UndoInfo, state->UpdatedStep[PositionIndex]);
  return ActionState::ptr(_state);
}
bool MoleculeVerletIntegrationAction::canUndo() {
  return true;
}
bool MoleculeVerletIntegrationAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */