/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2013 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 .
 */
/*
 * PythonScripting.cpp
 *
 *  Created on: Aug 26, 2013
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
// boost::python uses placement new which is incompatible with MemDebug.
#include "PythonScripting_impl.hpp"
#include "PythonScripting.hpp"
//#include "CodePatterns/MemDebug.hpp"
bool executePythonScriptFile(const boost::filesystem::path &pythonfilename)
{
  if (exists(pythonfilename)) {
    // parse file into a string
    std::ifstream pythonfile(pythonfilename.string().c_str());
    std::string pythonscript( std::istreambuf_iterator(pythonfile),
        (std::istreambuf_iterator()) );
    return executePythonScript(pythonscript, pythonfilename.string());
  }
  return false;
}
bool executePythonScript(const std::string &python_string, const std::string &python_scripttitle)
{
  std::stringstream input(python_string);
  std::stringstream buffer_import;
  std::stringstream buffer_else;
  // move all lines with "import" to the beginning
  std::string current_line;
  while(std::getline(input,current_line,'\n')){
    if (current_line.find("import ") != std::string::npos)
      buffer_import << current_line << std::endl;
    else
      buffer_else << current_line << std::endl;
  }
  std::string pythonscript_import( std::istreambuf_iterator(buffer_import),
      (std::istreambuf_iterator()) );
  std::string pythonscript_else( std::istreambuf_iterator(buffer_else),
      (std::istreambuf_iterator()) );
  try {
#ifdef HAVE_PYTHON2
    PyImport_AppendInittab( "pyMoleCuilder", &initpyMoleCuilder );
#else
    PyImport_AppendInittab( "pyMoleCuilder", &PyInit_pyMoleCuilder );
#endif
    Py_Initialize();
    boost::python::object main_module((
        boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__")))));
    boost::python::object main_namespace = main_module.attr("__dict__");
    boost::python::handle<> imported(( PyRun_String( pythonscript_import.c_str(),
        Py_file_input,
        main_namespace.ptr(),
        main_namespace.ptr() ) ));
    boost::python::object molecuilder_module( (boost::python::handle<>(PyImport_ImportModule("pyMoleCuilder"))) );
    main_namespace["pyMoleCuilder"] = molecuilder_module;
    std::string enveloped_script("print(\"BEGIN of "+python_scripttitle+":\")\n");
    enveloped_script += pythonscript_else+std::string("\n");
    enveloped_script += std::string("print(\"END of "+python_scripttitle+":\")\n");
    boost::python::handle<> ignored(( PyRun_String( enveloped_script.c_str(),
        Py_file_input,
        main_namespace.ptr(),
        main_namespace.ptr() ) ));
  } catch( boost::python::error_already_set ) {
    PyErr_Print();
    return false;
  }
  return true;
}