#include <stdio.h>
#include <WScom.h>
#include <WSCbase.h>
#include <WSCprocedure.h>
#include <WSCindexData.h>
#include <Python.h>
#include <compile.h>
#include <frameobject.h>

//extern VALUE mMpfc;
extern PyObject *pyptr;
WSCindexData flist;

void WSGFfunctionRegister(char* fname,PyObject* pyfunc){
  flist.setData(fname,(void*)pyfunc);
//printf("add %s pyfunc=0x%x fl=%d\n",fname,pyfunc, PyCallable_Check(pyfunc));
}

void _procedure_handler(char* fname,WSCbase* ptr){
  PyObject* pf = (PyObject*)flist.getData(fname);
  if (pf == NULL){
    fprintf(stderr,"procedure:%s not found.\n",fname);
    return;
  }
//printf("pf=0x%x\n",pf);
//  _PyObject_Dump(pf);
//printf("callable=%d\n",PyCallable_Check(pf));

  PyObject* obj = (PyObject*)ptr->getUserData("pyobj");
//printf("obj=0x%x\n",obj);
//  _PyObject_Dump(obj);

  PyObject* data = Py_BuildValue("(O)",obj);
  PyEval_CallObject(pf,data);

  Py_DECREF(data);


//printf("pfname=0x%x\n",pfname);
//  PyObject* pinstname = PyString_FromString(ptr->getInstanceName());
//printf("pinstname=0x%x\n",pinstname);
//  PyObject* pf = PyDict_GetItemString(f_globals,fname);
//  PyFrameObject* pf = (PyFrameObject*)PyEval_GetFrame();
//  PyObject* pf = PyEval_GetGlobals();
//  PyObject* pf = PyEval_GetLocals();
//  _PyObject_Dump(pf->f_locals);
//  _PyObject_Dump(pf->f_builtins);
//  VALUE  klass = rb_const_get(mMpfc, rb_intern("WSCbase"));
//  VALUE  obj = Data_Wrap_Struct(klass, 0, 0, ptr);
//  rb_funcall(NULL,rb_intern(fname),1,obj);
}

class _python_proc_init{
  public: _python_proc_init(){
    WSGFsetProcedureHandler((void*)_procedure_handler);
//printf("_python_proc_init...\n");
  };
};
_python_proc_init _exec_python_init;
