/*
 * 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 .
 */
/*
 * ConvexEnvelopeAction.cpp
 *
 *  Created on: May 12, 2010
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "CodePatterns/MemDebug.hpp"
#include "CodePatterns/Log.hpp"
#include "config.hpp"
#include "LinkedCell/linkedcell.hpp"
#include "LinkedCell/PointCloudAdaptor.hpp"
#include "molecule.hpp"
#include "Tesselation/boundary.hpp"
#include "Tesselation/tesselation.hpp"
#include "World.hpp"
#include 
#include 
#include "Actions/TesselationAction/ConvexEnvelopeAction.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "ConvexEnvelopeAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
ActionState::ptr TesselationConvexEnvelopeAction::performCall() {
  molecule * mol = NULL;
  bool Success = true;
  config *configuration = World::getInstance().getConfig();
  for (World::MoleculeSelectionIterator iter = World::getInstance().beginMoleculeSelection(); iter != World::getInstance().endMoleculeSelection(); ++iter) {
    mol = iter->second;
    class Tesselation *TesselStruct = NULL;
    const LinkedCell_deprecated *LCList = NULL;
    LOG(0, "Evaluating volume of the convex envelope.");
    LOG(1, "Storing tecplot convex data in " << params.filenameConvex.get() << ".");
    LOG(1, "Storing tecplot non-convex data in " << params.filenameNonConvex.get() << ".");
    PointCloudAdaptor cloud(mol, mol->name);
    LCList = new LinkedCell_deprecated(cloud, 2.*params.SphereRadius.get());
    //Boundaries *BoundaryPoints = NULL;
    //FindConvexBorder(mol, BoundaryPoints, TesselStruct, LCList, argv[argptr]);
    // TODO: Beide Funktionen sollten streams anstelle des Filenamen benutzen, besser fuer unit tests
    Success &= FindNonConvexBorder(mol, TesselStruct, LCList, params.SphereRadius.get(), params.filenameNonConvex.get().string().c_str());
    //RemoveAllBoundaryPoints(TesselStruct, mol, argv[argptr]);
    const double volumedifference =
        ConvexizeNonconvexEnvelope(TesselStruct, mol, params.filenameConvex.get().string().c_str(),
            params.DoOutputEveryStep.get());
    // check whether tesselated structure is truly convex
    if (!TesselStruct->isConvex()) {
      ELOG(1, "Tesselated surface has not been properly convexized.");
        Success = false;
    } else {
      LOG(2, "DEBUG: We do have a convex surface tesselation now.");
    }
    // we check whether all molecule's atoms are still inside
    std::vector outside_atoms;
    for(molecule::const_iterator iter = const_cast(mol)->begin();
        iter != const_cast(mol)->end(); ++iter)
      if (!TesselStruct->IsInnerPoint((*iter)->getPosition(), LCList))
        outside_atoms.push_back((*iter)->getName());
    if (outside_atoms.empty())
      LOG(2, "DEBUG: All molecule's atoms are inside the tesselated, convex surface.");
    else {
      ELOG(1, "The following atoms are not inside the tesselated, convex surface:"
          << outside_atoms);
      Success = false;
    }
    const double clustervolume = TesselStruct->getVolumeOfConvexEnvelope(configuration->GetIsAngstroem());
    LOG(0, "The tesselated volume area is " << clustervolume << " " << (configuration->GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3.");
    LOG(0, "The non-convex tesselated volume area is " << clustervolume-volumedifference << " " << (configuration->GetIsAngstroem() ? "angstrom" : "atomiclength") << "^3.");
    delete(TesselStruct);
    delete(LCList);
  }
  if (Success)
    return Action::success;
  else {
    STATUS(std::string("Failed to find the non convex border")
        +std::string("containing all atoms")
        +std::string("."));
    return Action::failure;
  }
}
ActionState::ptr TesselationConvexEnvelopeAction::performUndo(ActionState::ptr _state) {
//  TesselationConvexEnvelopeState *state = assert_cast(_state.get());
//  string newName = state->mol->getName();
//  state->mol->setName(state->lastName);
  STATUS("Undo of TesselationConvexEnvelopeAction not implemented.");
  return Action::failure;
}
ActionState::ptr TesselationConvexEnvelopeAction::performRedo(ActionState::ptr _state){
  // Undo and redo have to do the same for this action
  return performUndo(_state);
}
bool TesselationConvexEnvelopeAction::canUndo() {
  return false;
}
bool TesselationConvexEnvelopeAction::shouldUndo() {
  return false;
}
/** =========== end of function ====================== */