/* 
 * © 2009 Sun Microsystems, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "stdafx.h"

#include "grtpp_module_python.h"
#include "grtpp_util.h"

#ifdef ENABLE_PYTHON_MODULES

using namespace grt;

PythonModule::PythonModule(PythonModuleLoader *loader, PyObject *module)
: Module(loader), _module(module)
{
}


PythonModule::~PythonModule()
{
  Py_XDECREF(_module);
}


static TypeSpec parse_type(PyObject *type)
{
  if (PyString_Check(type))
  {
    TypeSpec s;
    s.base.type= str_to_type(PyString_AsString(type));
    return s;
  }
  PyErr_Clear();
  
  if (PyTuple_Check(type))
  {
    TypeSpec s;
    PyObject *b, *c;
    b= PyTuple_GetItem(type, 0);
    if (!b)
    {
      PyErr_Print();
      throw std::runtime_error("Invalid type specification");
    }
    c= PyTuple_GetItem(type, 1);
    if (!c)
    {
      PyErr_Print();
      throw std::runtime_error("Invalid type specification");
    }

    s.base.type= str_to_type(PyString_AsString(b));
    if (s.base.type == grt::ObjectType)
    {
      if (PyString_Check(c))
        s.base.object_class= PyString_AsString(c);
      else
        throw std::runtime_error("Invalid object type specification");
    }
    else
    {
      if (PyString_Check(c))
        s.content.type= str_to_type(PyString_AsString(c));
      else if (PyTuple_Check(c) && PyTuple_Size(c) == 2)
      {
        s.content.type= grt::ObjectType;
        s.content.object_class= PyString_AsString(PyTuple_GetItem(c, 1));
      }
      else
        throw std::runtime_error("Invalid type specification");
    }
    return s;
  }
  PyErr_Clear();
  
  throw std::runtime_error("Invalid type specification");
}


void PythonModule::add_parse_function(const std::string &name, PyObject *return_type, PyObject *arguments, PyObject *callable)
{
  Function func;
  
  func.name= name;
  try
  {
    func.ret_type= parse_type(return_type);
  }
  catch (std::exception)
  {
    throw std::runtime_error(strfmt("Invalid return type specification in %s.%s", _name.c_str(), name.c_str()));
  }
  
  for (Py_ssize_t c= PyList_Size(arguments), i= 0; i < c; i++)
  {
    PyObject *spec= PyList_GetItem(arguments, i);
    ArgSpec arg;
    PyObject *tmp;
    
    if (!PyTuple_Check(spec))
    {
      PyErr_Print();
      throw std::runtime_error("Invalid argument specification (argument spec must be list of tuples)");
    }
  
    tmp= PyTuple_GetItem(spec, 0);
    if (!tmp && !PyString_Check(tmp))
    {
      PyErr_Print();
      throw std::runtime_error("Invalid argument name specification");
    }
    arg.name= PyString_AsString(tmp);

    tmp= PyTuple_GetItem(spec, 1);
    if (!tmp)
    {
      PyErr_Print();
      throw std::runtime_error("Invalid argument type specification");
    }
    try
    {
      arg.type= parse_type(tmp);
    }
    catch (std::exception)
    {
      throw std::runtime_error(strfmt("Invalid argument type specification in %s.%s", _name.c_str(), name.c_str()));
    }
    func.arg_types.push_back(arg);
  }
  
  func.call= sigc::bind(sigc::mem_fun(this, &PythonModule::call_function), callable, func);
  
  add_function(func);
}


ValueRef PythonModule::call_function(const BaseListRef &args, PyObject *function, const Function &funcdef)
{
  PythonContext *ctx= ((PythonModuleLoader*)get_loader())->get_python_context();
  PyObject *argtuple;
  
  LockPython lock(ctx);
  
  if (args.is_valid())
  {
    argtuple= PyTuple_New(args.count());
    int i= 0;
    
    // convert arguments to a tuple that can be passed to the function
    for (BaseListRef::raw_const_iterator iter= args.begin(); iter != args.end(); ++iter)
      PyTuple_SetItem(argtuple, i++, ctx->from_grt(*iter));
  }
  else
  {
    argtuple= Py_None;
    Py_INCREF(Py_None);
  }
  
  // call the function
  PyObject *ret= PyObject_Call(function, argtuple, NULL);
  Py_DECREF(argtuple);

  if (!ret && PyErr_Occurred())
  {
    PyErr_Print();
    /* dont know how to fetch formatted traceback
    PyObject *exception, *v, *tb= NULL;
    PyErr_Fetch(&exception, &v, &tb);
    PyErr_NormalizeException(&exception, &v, &tb);
 
    PyObject *s = PyObject_Str(v);
    std::string error;
    if (s != NULL && PyString_Check(s))
      error= PyString_AsString(s);
  
    Py_XDECREF(exception);
    Py_XDECREF(v);
    Py_XDECREF(tb);
    */
    throw grt::module_error(strfmt("error calling %s.%s: see output for details", name().c_str(), funcdef.name.c_str()));
  }

  ValueRef result= ctx->from_pyobject(ret, funcdef.ret_type);
  
  Py_XDECREF(ret);
  
  return result;
}






PythonModuleLoader::PythonModuleLoader(GRT *grt)
: ModuleLoader(grt), _pycontext(grt)
{
}


PythonModuleLoader::~PythonModuleLoader()
{
}


Module *PythonModuleLoader::init_module(const std::string &path)
{
  PyObject *mod;
  std::string name;
  
  LockPython lock(&_pycontext);
  
  if (path.rfind('.') != std::string::npos)
    name= path.substr(0, path.rfind('.')); // strip extension
  else
    name= path;
  
  {
    gchar *n= g_path_get_basename(name.c_str());
    name= n;
    g_free(n);
  }
  
  {
    PyObject *old_path, *sysmod, *path_list;
    // temporarily add the file's path to the module lookup pat
    sysmod= PyImport_AddModule("sys");
  
    path_list= PyDict_GetItemString(PyModule_GetDict(sysmod), "path");
    old_path= PyList_GetSlice(path_list, 0, PyList_Size(path_list));
    {
      char *dir= g_path_get_dirname(path.c_str());
      PyObject *tmp= PyString_FromString(dir);
      PyList_Append(path_list, tmp);
      g_free(dir);
      Py_DECREF(tmp);
    }
    // import module
    mod= PyImport_ImportModule((char*)name.c_str());
    
    // restore path
    PyDict_SetItemString(PyModule_GetDict(sysmod), "path", old_path);
    Py_DECREF(old_path);
    if (mod == NULL)
    {
      PyErr_Print();
      return 0;
    }
  }

  {
    PyObject *module_dict= PyModule_GetDict(mod);
    PyObject *moduleInfo= NULL;

    moduleInfo= PyDict_GetItemString(module_dict, "ModuleInfo");
    if (!moduleInfo)
    {
      PyErr_Print();
      return 0;
    }
    if (!PyDict_Check(moduleInfo))
    {
      Py_XDECREF(moduleInfo);
      PyErr_Clear();
      throw grt::module_error("ModuleInfo is not a dictionary");
    }
    
    grt::PythonModule *module= new grt::PythonModule(this, mod);

    {
      PyObject *name;
      name= PyDict_GetItemString(moduleInfo, "name");
      if (PyString_Check(name))
        module->_name= PyString_AsString(name);
      else
        PyErr_Print();
    }
    
    
    PyObject *functions= PyDict_GetItemString(moduleInfo, "functions");
    if (PyList_Check(functions))
    {
      for (Py_ssize_t c= PyList_Size(functions), i= 0; i < c; i++)
      {
        PyObject *item= PyList_GetItem(functions, i);
        const char *name= 0;
        PyObject *rettype;
        PyObject *argtypes;
        PyObject *callable;

        if (!PyArg_ParseTuple(item, "z(OO!)O!", &name, &rettype, &PyList_Type, &argtypes, &PyFunction_Type, &callable))
        {
          PySys_WriteStderr("ERROR: Invalid module function specification in %s\n",
                            path.c_str());
          PyErr_Print();
          PyObject *tmp= PyTuple_GetItem(item, 0);
          if (tmp && PyString_Check(tmp))
          {
            PySys_WriteStderr("  for function %s.%s\n",
                              module->_name.c_str(), PyString_AsString(tmp));
          }
          PyErr_Clear();
          delete module;
          return 0;
        }

        try
        {
          module->add_parse_function(name?name:"", rettype, argtypes, callable);
        }
        catch (std::exception &exc)
        {
          delete module;
          throw grt::module_error(strfmt("Error registering Python module function: %s", exc.what()));
        }
      }
    }
    else
      PyErr_Print();
    
    PyObject *implements= PyDict_GetItemString(moduleInfo, "implements");
    if (!PyList_Check(implements))
    {
      PyErr_Print();
      delete module;
      throw grt::module_error("Invalid value for 'implements' list");
    }
    
    for (Py_ssize_t c= PyList_Size(implements), i= 0; i < c; i++)
    {
      PyObject *name= PyList_GetItem(implements, i);
      if (!PyString_Check(name))
      {
        PyErr_Print();
        delete module;
        throw grt::module_error("Invalid value for 'implements' list");
      }
      
      module->_interfaces.push_back(PyString_AsString(name));
    }
    
    PyObject *meta;

    meta= PyDict_GetItemString(moduleInfo, "author");
    if (PyString_Check(meta))
      module->_meta_author= PyString_AsString(meta);
    else
      PyErr_Print();
    
    meta= PyDict_GetItemString(moduleInfo, "version");
    if (PyString_Check(meta))
      module->_meta_version= PyString_AsString(meta);
    else
      PyErr_Print();
    
    meta= PyDict_GetItemString(moduleInfo, "description");
    if (PyString_Check(meta))
      module->_meta_description= PyString_AsString(meta);
    else
      PyErr_Print();
    
    return module;
  }
  
  return 0;
}


void PythonModuleLoader::refresh()
{
  _pycontext.refresh();
}


bool PythonModuleLoader::load_library(const std::string &file)
{
#if 0
  FILE *f= fopen(file.c_str(), "r");
  if (!f)
    return false;

  LockPython lock(&_pycontext);
  
  // execute in the global environment will make it available to the interactive shell
  if (PyRun_SimpleFile(f, file.c_str()) < 0)
  {
    fclose(f);
    PyErr_Print();
    return false;
  }
#endif
  // add the path to the search path so that it can be imported
  {
    gchar *dirname= g_path_get_dirname(file.c_str());    
    PyObject *sysmod, *path_list;
    PyObject *path= PyString_FromString(dirname);
    g_free(dirname);

    sysmod= PyImport_AddModule("sys");

    path_list= PyDict_GetItemString(PyModule_GetDict(sysmod), "path");
    Py_ssize_t i;

    // check if the path is already in it
    for (i= PyList_Size(path_list)-1; i >= 0; --i)
    {
      if (PyObject_Compare(PyList_GetItem(path_list, i), path) == 0)
        break;
    }

    if (i < 0) // not found
      PyList_Append(path_list, path);

    Py_DECREF(path);
  }

  return true;
}


bool PythonModuleLoader::run_script_file(const std::string &path)
{
  return load_library(path);
}


bool PythonModuleLoader::check_file_extension(const std::string &path)
{
  if (g_str_has_suffix(path.c_str(), ".py"))
    return true;

  return false;
}


#endif // ENABLE_PYTHON_MODULES

