/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2016 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 .
 */
/*
 * ParseFragmentResultsAction.cpp
 *
 *  Created on: Sep 04, 2016
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
// include headers that implement a archive in simple text format
// and before MemDebug due to placement new
#include 
#include 
#include "CodePatterns/MemDebug.hpp"
#include 
#include "CodePatterns/Assert.hpp"
#include "CodePatterns/Log.hpp"
#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
#include "Actions/FragmentationAction/ParseFragmentResultsAction.hpp"
using namespace MoleCuilder;
// and construct the stuff
#include "ParseFragmentResultsAction.def"
#include "Action_impl_pre.hpp"
/** =========== define the function ====================== */
static void secureFragmentResultsContentsInStream(std::ostream &_backupstream)
{
  FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
  boost::archive::text_oarchive oa(_backupstream);
  oa << container;
}
static void restoreFragmentResultsContentsFromStream(std::istream &_backupstream)
{
  FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
  boost::archive::text_iarchive ia(_backupstream);
  ia >> container;
}
bool parseFragmentResultsFromFile(
    const boost::filesystem::path &fragmentresults_file,
    std::stringstream &_backupstream
    )
{
  /// if file is given, parse from file into ResultsContainer
  FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
  // secure container contents
  secureFragmentResultsContentsInStream(_backupstream);
  if (boost::filesystem::exists(fragmentresults_file)) {
    LOG(1, "INFO: Parsing results from " << fragmentresults_file.string() << ".");
    std::ifstream filestream(fragmentresults_file.string().c_str());
    if (filestream.good()) {
      container.clear();
      restoreFragmentResultsContentsFromStream(filestream);
      if (filestream.bad()) { // check if correctly written
        LOG(1, "Failed to read from file " << fragmentresults_file.string() << ".");
        // restore container
        restoreFragmentResultsContentsFromStream(_backupstream);
        return false;
      } else {
        filestream.close();
#if not defined(HAVE_JOBMARKET) || not defined(HAVE_VMG)
        if (container.areFullRangeResultsPresent()) {
          ELOG(2, "Long-range information contained in results but long-range analysis capability not compiled in.");
        }
#endif
      }
    }
  } else {
    ELOG(1, "Given file " << fragmentresults_file.string() << " does not exist.");
    return false;
  }
  return true;
}
ActionState::ptr FragmentationParseFragmentResultsAction::performCall()
{
  if (!params.fragmentresults_file.get().empty()) {
    const boost::filesystem::path &fragmentresults_file = params.fragmentresults_file.get();
    std::stringstream backupstream;
    if (parseFragmentResultsFromFile(fragmentresults_file, backupstream)) {
      STATUS("SUCCESS: Parsed Fragment results from file "+toString(fragmentresults_file.string())+".");
      return ActionState::ptr(new FragmentationParseFragmentResultsState(backupstream.str(), params));
    } else {
      STATUS("FAIL: Failed to parse fragment results file.");
      return Action::failure;
    }
  } else {
    STATUS("FAIL: Fragment results file name is empty.");
    return Action::failure;
  }
}
ActionState::ptr FragmentationParseFragmentResultsAction::performUndo(ActionState::ptr _state) {
  FragmentationParseFragmentResultsState *state =
      assert_cast(_state.get());
  FragmentationResultContainer& container = FragmentationResultContainer::getInstance();
  std::stringstream contents(state->streamed_container);
  boost::archive::text_iarchive ia(contents);
  ia >> container;
  return ActionState::ptr(_state);
}
ActionState::ptr FragmentationParseFragmentResultsAction::performRedo(ActionState::ptr _state){
  FragmentationParseFragmentResultsState *state =
      assert_cast(_state.get());
  // we know that action suceeded before
  std::stringstream backupstream;
  bool status = parseFragmentResultsFromFile(state->params.fragmentresults_file.get(), backupstream);
  ASSERT( status,
      "FragmentationParseFragmentResultsAction::performRedo() - action failed although succeeded before?");
  return ActionState::ptr(_state);
}
bool FragmentationParseFragmentResultsAction::canUndo() {
  return true;
}
bool FragmentationParseFragmentResultsAction::shouldUndo() {
  return true;
}
/** =========== end of function ====================== */