/*
 * 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 .
 */
/*
 * FillSurfaceAction.cpp
 *
 *  Created on: Mar 29, 2012
 *      Author: heber, bollerhe
 */
// 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/CopyAtoms/CopyAtoms_withBonds.hpp"
#include "CodePatterns/Log.hpp"
#include "Filling/Cluster.hpp"
#include "Filling/Filler.hpp"
#include "Filling/Inserter/Inserter.hpp"
#include "Filling/Inserter/SurfaceInserter.hpp"
#include "Filling/Mesh/MeshAdaptor.hpp"
#include "Filling/Predicates/IsVoidNode_FillPredicate.hpp"
#include "Filling/Preparators/ShapeSurfaceFillerPreparator.hpp"
#include "molecule.hpp"
#include "Shapes/BaseShapes.hpp"
#include "Shapes/ShapeRegistry.hpp"
#include "Shapes/ShapeType.hpp"
#include "World.hpp"
#include 
#include 
#include 
#include 
#include 
#include 
#include "Actions/FillAction/FillSurfaceAction.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "FillSurfaceAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr FillSurfaceAction::performCall() {
  // get the filler molecule
  const std::vector< molecule *> molecules = World::getInstance().getSelectedMolecules();
  std::vector movedatoms;
  if (molecules.size() != 1) {
    STATUS("No exactly one molecule selected, aborting,");
    return Action::failure;
  }
  molecule *filler = *(molecules.begin());
  for(molecule::const_iterator iter = const_cast(filler)->begin();
      iter != const_cast(filler)->end(); ++iter)
    movedatoms.push_back( AtomicInfo(*(*iter)) );
  LOG(1, "INFO: Chosen molecule has " << filler->size() << " atoms.");
  // center filler's tip at origin
  filler->CenterEdge();
  // determine center with respect to alignment axis
  Vector sum = zeroVec;
  for (molecule::const_iterator it2=const_cast(filler)->begin();
      it2 !=const_cast(filler)->end();++it2) {
    const Vector helper = (**it2).getPosition().partition(params.AlignedAxis.get()).second;
    sum += helper;
  }
  sum *= 1./filler->size();
  // translate molecule's closest atom to origin (such that is resides on the filler spot)
  LOG(1, "DEBUG: molecule is off Alignment axis by " << sum << ", shifting ...");
  {
    Vector translater = -1.*sum;
    filler->Translate(translater);
  }
  // prepare the filler preparator
  if (ShapeRegistry::getInstance().countSelectedShapes() != (size_t)1) {
    STATUS("Not exactly one shape selected.");
    return Action::failure;
  }
  const std::vector shapes = ShapeRegistry::getInstance().getSelectedShapes();
  const Shape &shape = **shapes.begin();
  // hard check whether shape is of allowed type, not all are implemented
  // but these only fail with an assertion, hence not with disable-debug
  switch (shape.getType()) {
    case NowhereType:
    case EverywhereType:
      STATUS("The shape type "+toString(shape.getType())+" is currently not supported.");
      return Action::failure;
      break;
    default:
      break;
  }
  ShapeSurfaceFillerPreparator filler_preparator(filler);
  if (params.SphereRadius.get() != 0.) {
    if (World::getInstance().beginAtomSelection() == World::getInstance().endAtomSelection()) {
      STATUS("You have given a sphere radius "+toString(params.SphereRadius.get())
          +" != 0, but have not select any atoms.");
      return Action::failure;
    }
    std::vector atoms(World::getInstance().getSelectedAtoms());
    filler_preparator.addSurfacePredicate(
        params.SphereRadius.get(),
        atoms,
        params.mindistance.get());
  }
  filler_preparator.addVoidPredicate(params.mindistance.get());
  filler_preparator.addSurfaceRandomInserter(
      shape,
      params.AlignedAxis.get(),
      params.RandAtomDisplacement.get(),
      params.RandMoleculeDisplacement.get());
  filler_preparator.addShapeMesh(
      shape,
      params.N.get());
  if (!filler_preparator()) {
    STATUS("Filler was not fully constructed.");
    return Action::failure;
  }
  // use filler
  bool successflag = false;
  FillSurfaceState *UndoState = NULL;
  {
    // fill
    {
      Filler *fillerFunction = filler_preparator.obtainFiller();
      ClusterInterface::Cluster_impl cluster( new Cluster( filler->getAtomIds(), filler->getBoundingSphere() ) );
      CopyAtoms_withBonds copyMethod;
      Filler::ClusterVector_t ClonedClusters;
      successflag = (*fillerFunction)(copyMethod, cluster, ClonedClusters);
      delete fillerFunction;
      // append each cluster's atoms to clonedatoms (however not selected ones)
      std::vector clonedatoms;
      std::vector clonedatominfos;
      for (Filler::ClusterVector_t::const_iterator iter = ClonedClusters.begin();
          iter != ClonedClusters.end(); ++iter) {
        const AtomIdSet &atoms = (*iter)->getAtomIds();
        clonedatoms.reserve(clonedatoms.size()+atoms.size());
        for (AtomIdSet::const_iterator atomiter = atoms.begin(); atomiter != atoms.end(); ++atomiter)
          if (!filler->containsAtom(*atomiter)) {
            clonedatoms.push_back( *atomiter );
            clonedatominfos.push_back( AtomicInfo(*(*atomiter)) );
          }
      }
      std::vector< BondInfo > clonedbonds;
      StoreBondInformationFromAtoms(clonedatoms, clonedbonds);
      LOG(2, "DEBUG: There are " << clonedatominfos.size() << " newly created atoms with "
          << clonedbonds.size()/2 << " bonds.");
      if (!successflag) {
        STATUS("Insertion failed, removing inserted clusters, translating original one back");
        RemoveAtomsFromAtomicInfo(clonedatominfos);
        clonedatoms.clear();
        SetAtomsFromAtomicInfo(movedatoms);
      } else {
        std::vector MovedToVector(filler->size(), zeroVec);
        std::transform(filler->begin(), filler->end(), MovedToVector.begin(),
            boost::bind(&AtomInfo::getPosition, _1) );
        UndoState = new FillSurfaceState(clonedatominfos,clonedbonds,movedatoms,MovedToVector,params);
      }
    }
  }
  if (successflag)
    return ActionState::ptr(UndoState);
  else
    return Action::failure;
}
ActionState::ptr FillSurfaceAction::performUndo(ActionState::ptr _state) {
  FillSurfaceState *state = assert_cast(_state.get());
  // remove all created atoms
  RemoveAtomsFromAtomicInfo(state->clonedatoms);
  // add the original cluster
  SetAtomsFromAtomicInfo(state->movedatoms);
  return ActionState::ptr(_state);
}
ActionState::ptr FillSurfaceAction::performRedo(ActionState::ptr _state){
  FillSurfaceState *state = assert_cast(_state.get());
  // place filler cluster again at new spot
  ResetAtomPosition(state->movedatoms, state->MovedToVector);
  // re-create all clusters
  bool statusflag = AddAtomsFromAtomicInfo(state->clonedatoms);
  // re-create the bonds
  statusflag = statusflag && AddBondsFromBondInfo(state->clonedbonds);
  if (statusflag)
    return ActionState::ptr(_state);
  else {
    STATUS("Failed to re-added filled in atoms.");
    return Action::failure;
  }
}
bool FillSurfaceAction::canUndo() {
  return true;
}
bool FillSurfaceAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */