/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2015 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 .
 */
/*
 * SaturateAction.cpp
 *
 *  Created on: Jan 26, 2015
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "CodePatterns/MemDebug.hpp"
#include "CodePatterns/Log.hpp"
#include "Actions/AtomAction/SaturateAction.hpp"
#include "Actions/UndoRedoHelpers.hpp"
#include "Atom/atom.hpp"
#include "Atom/AtomicInfo.hpp"
#include "Element/element.hpp"
#include "Element/periodentafel.hpp"
#include "Fragmentation/Exporters/SphericalPointDistribution.hpp"
#include "molecule.hpp"
#include "World.hpp"
#include "WorldTime.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "SaturateAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr AtomSaturateAction::performCall() {
  // get hydrogen element
  const element * const hydrogen = World::getInstance().getPeriode()->FindElement(1);
  // go through each atom
  std::vector addedHydrogens;
  World &world = World::getInstance();
  for (World::AtomSelectionIterator iter = world.beginAtomSelection();
      iter != world.endAtomSelection(); ++iter) {
    atom * const _atom = iter->second;
    // if atom is attached to molecule, add hydrogens there, too
    molecule * mol = NULL;
    if (_atom->getMolecule() == NULL) {
      mol = World::getInstance().createMolecule();
      mol->AddAtom(_atom);
    } else {
      mol = World::getInstance().getMolecule(MoleculeById(_atom->getMolecule()->getId()));
    }
    ASSERT( mol != NULL,
        "AtomSaturateAction::performCall() - mol is still NULL." );
    // radius of polygon on sphere
    double typical_distance = _atom->getType()->getHBondDistance(0);
    if (typical_distance == -1.)
      typical_distance = 1.;
    // check for any bonds and get vacant positions
    SphericalPointDistribution::Polygon_t vacant_positions;
    const BondList& ListOfBonds = _atom->getListOfBonds();
    SphericalPointDistribution PointSphere(typical_distance);
    if (ListOfBonds.size() == 0) {
      vacant_positions = PointSphere.getSimplePolygon(_atom->getType()->getNoValenceOrbitals());
      LOG(3, "DEBUG: Using ideal positions as " << vacant_positions);
    } else {
      // get ideal polygon and currently occupied positions
      const SphericalPointDistribution::Polygon_t ideal_positions =
          PointSphere.getSimplePolygon(_atom->getType()->getNoValenceOrbitals());
      LOG(3, "DEBUG: ideal positions are " << ideal_positions);
      SphericalPointDistribution::WeightedPolygon_t current_positions;
      for (BondList::const_iterator bonditer = ListOfBonds.begin();
          bonditer != ListOfBonds.end(); ++bonditer) {
        const Vector position =
            (*bonditer)->GetOtherAtom(_atom)->getPosition().getVectorToPoint(_atom->getPosition());
        current_positions.push_back(
            std::make_pair( (1./position.Norm())*position, (*bonditer)->getDegree() ));
      }
      LOG(3, "DEBUG: current occupied positions are " << current_positions);
      // find the best matching rotated polygon
      vacant_positions = PointSphere.getRemainingPoints(
          current_positions,
          _atom->getType()->getNoValenceOrbitals());
      LOG(3, "DEBUG: Resulting vacant positions are " << vacant_positions);
      // scale vacant positions to typical_distance
      std::for_each(
          vacant_positions.begin(), vacant_positions.end(),
          boost::bind(&Vector::Scale, _1, boost::cref(typical_distance)));
      LOG(3, "DEBUG: Rescaled vacant positions are " << vacant_positions);
    }
    // add the hydrogens
    const Vector AtomsPosition = _atom->getPosition();
    for (SphericalPointDistribution::Polygon_t::const_iterator iter = vacant_positions.begin();
        iter != vacant_positions.end(); ++iter) {
      // for every Vector add a point relative to atom's position
      atom * hydrogenAtom = World::getInstance().createAtom();
      hydrogenAtom->setType(hydrogen);
      hydrogenAtom->setPosition(AtomsPosition + *iter);
      mol->AddAtom(hydrogenAtom);
      // add bond
      _atom->addBond(WorldTime::getTime(), hydrogenAtom);
      // mark down for undo state
      addedHydrogens.push_back(AtomicInfo(*(hydrogenAtom)));
    }
  }
  return ActionState::ptr(new AtomSaturateState(addedHydrogens, params));
}
ActionState::ptr AtomSaturateAction::performUndo(ActionState::ptr _state) {
  AtomSaturateState *state = assert_cast(_state.get());
  // remove all added hydrogen atoms
  RemoveAtomsFromAtomicInfo(state->addedHydrogens);
  return ActionState::ptr(_state);
}
ActionState::ptr AtomSaturateAction::performRedo(ActionState::ptr _state){
  AtomSaturateState *state = assert_cast(_state.get());
  // re-add all added hydrogen atoms
  AddAtomsFromAtomicInfo(state->addedHydrogens);
  return ActionState::ptr(_state);
}
bool AtomSaturateAction::canUndo() {
  return true;
}
bool AtomSaturateAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */