#include <Python.h>
#include <QApplication>
#include <QWidget>

PyObject* call_function(PyObject *callable, PyObject *args)
{
    PyObject *result = NULL, *pArgs;
    if (callable == NULL){
        return NULL;
    }

    if (PyCallable_Check(callable)){
        if (args == NULL){
            pArgs = PyTuple_New(0);
        }else{
            pArgs = args;
        }
        result = PyObject_CallObject(callable, pArgs);
        if (args == NULL){
            Py_XDECREF(pArgs);
        }
        if (result == NULL){
            PyErr_Clear();
        }
    }
    return result;
}


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QString strString =  QString("import PyQt5.QtGui, PyQt5.QtWidgets, sip \n"
                                 "def getEmbeddedWidget():\n"
                                 "    widget = Screen()\n"
                                 "    return sip.unwrapinstance(widget)\n" );
    Py_Initialize();
    PyObject *pyModule = PyImport_ImportModule("Screen");

    if( !pyModule ){
        return -1;
    }

    PyObject *pyDict = PyModule_GetDict(pyModule);
    PyRun_String(strString.toStdString().c_str(), Py_file_input, pyDict, pyDict);
    PyObject *pyFactory = PyDict_GetItemString(pyDict, "getEmbeddedWidget");

    if( !pyFactory ){
        return -1;
    }
    PyObject *pyWidgetPtr = call_function(pyFactory, 0 );
    if (pyWidgetPtr)
    {
        QWidget *widget = (QWidget*)PyLong_AsVoidPtr(pyWidgetPtr);
        if( widget){
        }else{
            return -1;
        }
        // Decrement the reference count of the long value.
        Py_XDECREF(pyWidgetPtr);
        widget->show();
    }
    else{
        return -1;
    }
    int result = app.exec();
    return result;
}

