/*
 * 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 .
 */
/*
 * FillVolumeAction.cpp
 *
 *  Created on: Sep 03, 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/CopyAtoms/CopyAtoms_withBonds.hpp"
#include "Bond/BondInfo.hpp"
#include "CodePatterns/Log.hpp"
#include "Descriptors/MoleculeOrderDescriptor.hpp"
#include "Filling/Cluster.hpp"
#include "Filling/Filler.hpp"
#include "Filling/Preparators/ShapeVolumeFillerPreparator.hpp"
#include "molecule.hpp"
#include "Parser/FormatParserInterface.hpp"
#include "Parser/FormatParserStorage.hpp"
#include "Shapes/Shape.hpp"
#include "Shapes/ShapeRegistry.hpp"
#include "Shapes/ShapeType.hpp"
#include "World.hpp"
#include 
#include 
#include 
#include 
#include "Actions/FillAction/FillVolumeAction.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "FillVolumeAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr FillVolumeAction::performCall() {
  // get the filler molecule
  std::vector movedatoms;
  const std::vector< molecule *> molecules = World::getInstance().getSelectedMolecules();
  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();
  // 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:
    case SphereType:
    case CuboidType:
      STATUS("The shape type "+toString(shape.getType())+" is currently not supported.");
      return Action::failure;
      break;
    default:
      break;
  }
  ShapeVolumeFillerPreparator 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.addRandomInserter(
      params.RandAtomDisplacement.get(),
      params.RandMoleculeDisplacement.get(),
      params.DoRotate.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;
  FillVolumeState *UndoState = NULL;
  {
    // fill
    Filler *fillerFunction = filler_preparator.obtainFiller();
    // TODO: When molecule::getBoundingSphere() does not use a sphere anymore,
    // we need to check whether we rotate the molecule randomly. For this to
    // work we need a sphere!
    const Shape s = filler->getBoundingSphere(params.RandAtomDisplacement.get());
    ClusterInterface::Cluster_impl cluster( new Cluster(filler->getAtomIds(), s) );
    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.");
    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 FillVolumeState(clonedatominfos,clonedbonds,movedatoms,MovedToVector,params);
    }
  }
  if (successflag)
    return ActionState::ptr(UndoState);
  else {
    return Action::failure;
  }
}
ActionState::ptr FillVolumeAction::performUndo(ActionState::ptr _state) {
  FillVolumeState *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 FillVolumeAction::performRedo(ActionState::ptr _state){
  FillVolumeState *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
  if (statusflag)
    AddBondsFromBondInfo(state->clonedbonds);
  if (statusflag)
    return ActionState::ptr(_state);
  else {
    STATUS("Failed re-adding filled in atoms.");
    return Action::failure;
  }
}
bool FillVolumeAction::canUndo() {
  return true;
}
bool FillVolumeAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */