/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2010-2012 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 .
 */
/*
 * FillWithMoleculeAction.cpp
 *
 *  Created on: May 10, 2010
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "CodePatterns/MemDebug.hpp"
#include "Atom/atom.hpp"
#include "CodePatterns/Verbose.hpp"
#include "Descriptors/MoleculeIdDescriptor.hpp"
#include "Descriptors/MoleculeOrderDescriptor.hpp"
#include "Graph/BondGraph.hpp"
#include "molecule.hpp"
#include "MoleculeListClass.hpp"
#include "Parser/FormatParserInterface.hpp"
#include "Parser/FormatParserStorage.hpp"
#include "Tesselation/boundary.hpp"
#include "World.hpp"
#include 
#include 
#include "Actions/MoleculeAction/FillWithMoleculeAction.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "FillWithMoleculeAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
Action::state_ptr MoleculeFillWithMoleculeAction::performCall() {
  LOG(1, "INFO: Filling Box with water molecules, "
      << " minimum distance to molecules" << params.boundary.get()
      << ", random atom displacement " << params.RandAtomDisplacement.get()
      << ", random molecule displacement " << params.RandMoleculeDisplacement.get()
      << ", distances between fillers (" << params.distances.get()[0] << "," << params.distances.get()[1] << "," << params.distances.get()[2]
      << "), MinDistance " << params.MaxDistance.get()
      << ", DoRotate " << params.DoRotate.get() << ".");
  // construct water molecule
  std::vector presentmolecules = World::getInstance().getAllMolecules();
//  LOG(0, presentmolecules.size() << " molecules initially are present.");
  std::string FilenameSuffix = params.fillername.get().string().substr(params.fillername.get().string().find_last_of('.')+1, params.fillername.get().string().length());
  ifstream input;
  LOG(0, "STATUS: Loading filler molecule " << params.fillername.get().string().c_str()
      << " of suffix " << FilenameSuffix << ".");
  input.open(params.fillername.get().string().c_str());
  FormatParserStorage::getInstance().load(input, FilenameSuffix);
  input.close();
  // search the filler molecule that has been just parsed
  molecule *filler = World::getInstance().getMolecule(MoleculeByOrder(-1)); // get last molecule
  ASSERT(filler != NULL,
      "MoleculeFillWithMoleculeAction::performCall() - no last molecule found, nothing parsed?.");
  filler->SetNameFromFilename(params.fillername.get().string().c_str());
  World::AtomComposite Set = filler->getAtomSet();
  LOG(1, "INFO: The filler molecules has " << Set.size() << " atoms.");
  World::getInstance().getBondGraph()->CreateAdjacency(Set);
  // TODO: Remove the erasure of molecule when saving does not depend on them anymore.
  World::getInstance().getMolecules()->erase(filler); // remove it, Parser adds it automatically
  // call routine
  double distance[NDIM];
  for (int i=0;ibegin(); !filler->empty(); iter = filler->begin()) {
    atom *Walker = *iter;
    World::getInstance().destroyAtom(Walker);
  }
  World::getInstance().destroyMolecule(filler);
  // generate list of newly created molecules
  // (we can in general remove more quickly from a list than a vector)
  std::vector fillermolecules = World::getInstance().getAllMolecules();
//  LOG(0, fillermolecules.size() << " molecules are present.");
  std::list fillermolecules_list;
  std::copy( fillermolecules.begin(),  fillermolecules.end(), std::back_inserter( fillermolecules_list ));
//  LOG(0, fillermolecules_list.size() << " molecules have been copied.");
  for (std::vector::const_iterator iter = presentmolecules.begin();
      iter != presentmolecules.end();
      ++iter) {
    fillermolecules_list.remove(*iter);
  }
//  LOG(0, fillermolecules_list.size() << " molecules left after removal.");
  fillermolecules.clear();
  std::copy(fillermolecules_list.begin(), fillermolecules_list.end(), std::back_inserter( fillermolecules ));
//  LOG(0, fillermolecules.size() << " molecules have been inserted.");
  return Action::state_ptr(new MoleculeFillWithMoleculeState(fillermolecules,params));
}
Action::state_ptr MoleculeFillWithMoleculeAction::performUndo(Action::state_ptr _state) {
  MoleculeFillWithMoleculeState *state = assert_cast(_state.get());
  MoleculeListClass *MolList = World::getInstance().getMolecules();
  BOOST_FOREACH(molecule *_mol, state->fillermolecules) {
    MolList->erase(_mol);
    if ((_mol != NULL) && (!(World::getInstance().getAllMolecules(MoleculeById(_mol->getId()))).empty())) {
      for(molecule::iterator iter = _mol->begin();
          !_mol->empty();
          iter = _mol->begin()) {
        atom *Walker = *iter;
        World::getInstance().destroyAtom(Walker);
      }
      World::getInstance().destroyMolecule(_mol);
    }
  }
  // as molecules and atoms from state are removed, we have to create a new one
  std::vector fillermolecules;
  return Action::state_ptr(new MoleculeFillWithMoleculeState(fillermolecules,state->params));
}
Action::state_ptr MoleculeFillWithMoleculeAction::performRedo(Action::state_ptr _state){
  //MoleculeFillWithMoleculeState *state = assert_cast(_state.get());
  return Action::failure;
  //return Action::state_ptr(_state);
}
bool MoleculeFillWithMoleculeAction::canUndo() {
  return true;
}
bool MoleculeFillWithMoleculeAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */