/* This file is part of the Tomographer project, which is distributed under the
 * terms of the MIT license.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist
 * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */


#include <tomographerpy/common.h>
#include "common_p.h"

#include <pybind11/stl.h>

#include <tomographerpy/exc.h>


#include <tomographer/tomographer_version.h>

#ifdef TOMOGRAPHERPY_HAVE_COMPILEINFO
// file is auto-generated by setup.py
#  include "tomographerpy_compileinfo.h"
#endif



//void register_eigen_converter();

void py_tomo_histogram(py::module rootmodule);
void py_tomo_multiproc(py::module rootmodule);
void py_tomo_densedm(py::module rootmodule);
void py_tomo_tomorun(py::module rootmodule);
void py_tomo_mhrw(py::module rootmodule);
void py_tomo_mhrwtasks(py::module rootmodule);




namespace tpy
{
// common logger object
PyLogger * logger;

// the main exception object
py::object TomographerCxxErrorObj;
}




PYBIND11_PLUGIN(_tomographer_cxx)
{
#if PY_MAJOR_VERSION >= 3
  py::module rootmodule("tomographer", "Tomographer module"); // works
#else // 2.7
  py::module rootmodule("_tomographer_cxx", "Tomographer module");
  // hack module name so that classes, objects, etc. appear in the module "tomographer"
  rootmodule.attr("__name__") = py::bytes(std::string("tomographer"));
#endif

  py::options options;
  options.disable_function_signatures();

  tpy::logger = new tpy::PyLogger;

  // python logging
  tpy::logger->initPythonLogger();
  auto logger = Tomographer::Logger::makeLocalLogger(TOMO_ORIGIN, *tpy::logger);

  logger.debug("INIT TOMOGRAPHER");

  // our basic library exception class
  tpy::TomographerCxxErrorObj = tpy::registerExceptionWithDocstring<tpy::TomographerCxxError>(
      rootmodule,
      "TomographerCxxError",
      PyExc_RuntimeError,
      // doc:
      "Run-time error indicating an inappropriate usage or call of a method of the Python tomographer "
      "API.\n\n"
      );

  tpy::registerExceptionWithDocstring<Tomographer::Tools::EigenAssertException>(
      rootmodule,
      "EigenAssertError",
      tpy::TomographerCxxErrorObj.ptr(),
      // doc:
      "This exception indicates a C++ Eigen assertion failure generated by ``eigen_assert()``.  For instance, "
      "an index may be out of range."
      ) ;


  // expose Python API for setting the C++ logger level -- use shared_ptr as holder type
  py::class_<tpy::PyLogger,std::shared_ptr<tpy::PyLogger> >(rootmodule, "PyLogger")
    .def_property("level",
                  [](const tpy::PyLogger & l) { return l.toPythonLevel(l.level()); },
                  [](tpy::PyLogger & l, py::object newlevel) {
                    l.setLevel(l.fromPythonLevel(newlevel));
                  })
    .def("__repr__",
         [](const tpy::PyLogger & l) {
           return std::string("<PyLogger level=logging.") + l.toPythonLevelName(l.level()).cast<std::string>()
             + std::string(">");
         }
        )
    ;
  
  // PyBind11 will take over ownership of the object
  rootmodule.attr("cxxlogger") = tpy::logger;


  // the version of this library module
  rootmodule.attr("__version__") = TOMOGRAPHER_VERSION;
  // add a version submodule with more precise version info
  logger.debug("version module ... ");
  py::module versionmodule = rootmodule.def_submodule("version", "Version information");
  {
    versionmodule.attr("version_str") = TOMOGRAPHER_VERSION;

    auto collections = py::module::import("collections");
    auto namedtuple = collections.attr("namedtuple");
    py::list verfields;
    verfields.append("major"); 
    verfields.append("minor");
    auto VersionInfoTuple = namedtuple("VersionInfo", verfields);
    versionmodule.attr("version_info") = VersionInfoTuple(TOMOGRAPHER_VERSION_MAJ, TOMOGRAPHER_VERSION_MIN);

    // add compile_info
    py::dict compile_info;

#ifdef TOMOGRAPHERPY_HAVE_COMPILEINFO
    std::vector<std::string> compile_cflags = tomographerpy_compileinfo_get_cflags();
    compile_info["cflags"_s] = py::cast(compile_cflags);
    py::dict compiler_info = tomographerpy_compileinfo_get_compiler();
#else
    compile_info["cflags"_s] = py::none();
    py::dict compiler_info;
#endif
    compiler_info["desc"_s] = py::cast(TOMOGRAPHER_COMPILER_INFO_STR);
    compile_info["compiler"_s] = compiler_info;

    compile_info["eigen"_s] = Tomographer::Tools::fmts("Eigen %d.%d.%d (SIMD: %s)\n", EIGEN_WORLD_VERSION,
                                                       EIGEN_MAJOR_VERSION, EIGEN_MINOR_VERSION,
                                                       Eigen::SimdInstructionSetsInUse()) ;
    compile_info["boost"_s] = std::string(BOOST_LIB_VERSION);

// this needs to be in 2 steps or else we get "PYBIND11_VERSION_MAJOR.PYBIND11_VERSION_MINOR.PYBIND11_VERSION_PATCH"
#define VERSION_CAT(x,y,z) #x "." #y "." #z
#define FULL_PYBIND11_VERSION_STR(x,y,z) VERSION_CAT(x,y,z)
    compile_info["pybind11"_s] = std::string( FULL_PYBIND11_VERSION_STR(PYBIND11_VERSION_MAJOR,
                                                                        PYBIND11_VERSION_MINOR,
                                                                        PYBIND11_VERSION_PATCH) ) ;

    versionmodule.attr("compile_info") = compile_info;
  }

  logger.debug("Registering components ...");

  py_tomo_histogram(rootmodule);

  py_tomo_mhrw(rootmodule);

  py_tomo_multiproc(rootmodule);

  py_tomo_densedm(rootmodule);

  py_tomo_mhrwtasks(rootmodule);

  py_tomo_tomorun(rootmodule);

  logger.debug("TOMOGRAPHER INIT COMPLETE.");

  return rootmodule.ptr();
}
