#include <QObject>

#include "EmitSignal.h"
#include "smokephp.h"

extern void smokeStackToQtStack(const Smoke::Stack stack, void ** o, const int items, MocArgument* args);
extern Marshall::HandlerFn getMarshallFn(const SmokeType &type);

EmitSignal::EmitSignal(QObject *obj, const int id, const int items, MocArgument *mocStack, zval **sp, zval * result) :
  _obj(obj), _id(id), _cur(0), _called(false)
{
    _items = items;
    _args = mocStack;
//    _id = id;
    _sp = sp;
    _result = result;
    _stack = new Smoke::StackItem[ items ];
}

EmitSignal::~EmitSignal()
{
    delete[] _stack;
    
}

Marshall::Action
EmitSignal::action()
{
    return Marshall::FromZVAL;
}

Smoke::StackItem &
EmitSignal::item()
{
    return _stack[_cur];
}

const char *
EmitSignal::mytype()
{
    return "signal";
}

void
EmitSignal::emitSignal()
{
    if (_called) return;
    _called = true;
    void ** o = new void*[_items];
    smokeStackToQtStack(_stack, o + 1, _items, _args + 1);
    _obj->metaObject()->activate(_obj, _id, o);
    delete[] o;
}

void
EmitSignal::mainfunction()
{
    emitSignal();
}

bool
EmitSignal::cleanup()
{
    return true;
}

SmokeType
EmitSignal::type()
{
    return arg().st;
}

zval*
EmitSignal::var()
{
    return _sp[ _cur-1 ];
}

Smoke *
EmitSignal::smoke()
{
    return type().smoke();
}

void
EmitSignal::unsupported()
{
	php_error(E_ERROR, "Cannot handle '%s' as %s argument\n", type().name(), mytype() );
}

const MocArgument &
EmitSignal::arg()
{
	return _args[_cur];
}

void
EmitSignal::next()
{
	const int oldcur = _cur;
	_cur++;

	while(!_called && _cur <= _items) {
	  Marshall::HandlerFn fn = getMarshallFn(type());
	  (*fn)(this);
	  _cur++;
	}
	emitSignal();
	_cur = oldcur;
}

