#include "qgpython.h"

#include <QDebug>

static PythonQtObjectPtr qgpy_app_module;

QgPython::QgPython():
    mainWindow(0)
{    
    PythonQt::init(PythonQt::RedirectStdOut|PythonQt::IgnoreSiteModule);
}

void QgPython::initialize()
{
}

QgPython& QgPython::instance()
{
    static QgPython pyInstance;

    return pyInstance;
}

PythonQt& QgPython::self() const
{
    return *PythonQt::self();
}

PythonQtObjectPtr QgPython::mainContext()
{
    PythonQtObjectPtr  mainContext = PythonQt::self()->getMainModule();
    return mainContext;
}

PythonQtObjectPtr QgPython::createMainApplicationModule(const QString& module_name)
{
    if (!qgpy_app_module)
    {
        if (!module_name.isEmpty())
        {
            qgpy_app_module=QgPython::instance().self().createModuleFromScript(module_name,QString(""));
        }
        if (qgpy_app_module==0)
            qgpy_app_module=mainContext();
        else
            mainContext().evalScript(QString("import %1").arg(module_name));
    }

    return qgpy_app_module;
}

PythonQtObjectPtr QgPython::mainModule()
{
    if (!qgpy_app_module)
    {
        qgpy_app_module=mainContext();
    }
    return qgpy_app_module;
}

#include <QLibrary>

typedef void (*PythonQt_QtAll_Initialize_t)(void);

static PythonQt_QtAll_Initialize_t qtall_init;

void QgPython::importQtAll()
{
    if (qtall_init)
    {
        qDebug()<<"QgPy:"<<"QtAll already initialized";
        return;
    }
    QString ver=QString("%1").arg(QGPY_VERSION);
#if !defined(QT_NO_DEBUG)
    QLibrary pyall("PythonQt_QtAll-Qt5-Python"+ver+"_d");
#else
    QLibrary pyall("PythonQt_QtAll-Qt5-Python"+ver);
#endif

    bool ok=pyall.load();
    if (!ok)
    {
        qWarning()<<"QgPy:"<<"Cannot load QtAll:"<<pyall.errorString();
        return;
    }
    qtall_init=(PythonQt_QtAll_Initialize_t)pyall.resolve("PythonQt_QtAll_Initialize");
    if (!qtall_init)
    {
        qWarning()<<"QgPy:"<<"Cannot resolve QtAll initializer:"<<pyall.errorString();
        return;
    }
    qtall_init();
}

#include <QMainWindow>
#include <QWidget>
#include <QApplication>

QObject* QgPython::mw() const
{
    if (mainWindow==0)
    {
        foreach(QWidget *widget, qApp->topLevelWidgets())
            if (QMainWindow* mainW = qobject_cast<QMainWindow*>(widget))
            {
                mainWindow=mainW;
                return mainWindow;
            }
        return 0;
    }
    return mainWindow;
}

void QgPython::setMainWindow(QObject *w)
{
    mainWindow=w;
}
