/*
 * Project: QFitsView
 * File:    events.cpp
 * Purpose: Communication events between QFitsView GUI and DPUSER
 * Author:  Thomas Ott
 * History: August 20, 2004: File created
 *             May 31, 2005: Add function "injectVariable"
 */

#include "events.h"
#include "dpuser.h"
#include "dpuser.yacchelper.h"
#include "qtdpuser.h"
#include "fits.h"
#include "QFitsGlobal.h"

extern int scriptlock;
extern std::map<std::string, bool>loopVariables;

void dpUpdateVar(const std::string what) {
    if ((QString(what.c_str()).right(13) == "_standardstar") ||
        (QString(what.c_str()).left(1) == "_"))
        return;

        if (looplock == 0)
            dpuserthread.sendVar(what);
        else
            loopVariables[what] = true;
//	if (looplock == 0 && scriptlock == 0) {
//		dpDpuserEvent *ev = new dpDpuserEvent(what);
//		if (fitsMainWindow) QApplication::postEvent(fitsMainWindow, ev);
//	}
}

void dpUpdateView(const std::string what) {
    dpuserthread.sendView(what);
}

void dpCommandQFitsView(const char *what, const char *args, const int &option) {
    dpuserthread.sendCommand(what, args, option);
}

void dpProgress(const int what, const char *text) {
	dpuserthread.sendProgress(what, text);
//	QString str = text;
//	dpProgressEvent *ev = new dpProgressEvent(what, str);
//	QApplication::postEvent(fitsMainWindow, ev);
}

/*
 * inject a new variable in the dpuser working thread.
 * The variable will be of type FITS and initialised with
 * a copy of given data.
 * This bypasses the event loop, so the variable will NOT be
 * displayed automatically. To display, add the following code after
 * the call to injectVariable:
 *     QString cmd = "view " + name;
 *     dpuser_widget->executeCommand(cmd);
 */
std::string injectVariable(const QString &name, const Fits &data) {
    std::string rv;
	
        QWriteLocker locker(&buffersLock);
//	dpusermutex->lock();
    rv = name.toStdString();
    dpuser_vars[rv].type = typeFits;
    dpuser_vars[rv].fvalue = new Fits();
    dpuser_vars[rv].fvalue->copy(data);
//	dpusermutex->unlock();
	
	return rv;
}

