#include "qSystempi.h"
#include "piInstance.h"
#include "qPIWidget.h"
#include "mainwgt.h"
#include <stdio.h>
#include <resourceIo.h>

qSystem::qSystem()
{
    receiver = 0;
    qnpi = 0;
}

qSystem::qSystem( QNPInstance * tinstance)
{
    qnpi = tinstance;
    //can't do this yet. need to wait until the mainWgt is constructed.
    //receiver = ((piInstance *)qnpi)->iv->receiver();
    receiver = 0;
}

void qSystem::inform(const char *fmt, ...)
{
    static char lastbuf[1024] = { 0 };
    char buf[1024];

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf, fmt, ap);
    va_end(ap);
    if (strcmp(lastbuf, buf))
    {
        //temp for plugin debug
        fprintf(stderr,"(theSystem)");
        vfprintf(stderr, fmt, ap);
        if (receiver){
            receiver->sys_mesg(buf);
            strcpy(lastbuf, buf);
        }
    }
}

void qSystem::error(const char *fmt, ...)
{
    static char lastbuf[1024] = { 0 };
    char buf[1024];

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf, fmt, ap);
    va_end(ap);
    if (strcmp(lastbuf, buf))
    {
        //temp for plugin debug
        fprintf(stderr,"(theSystem)");
        vfprintf(stderr, fmt, ap);
        if (receiver){
            receiver->sys_mesg(buf);
            strcpy(lastbuf, buf);
        }
    }
}

void qSystem::warn(const char *fmt, ...)
{
    static char lastbuf[1024] = { 0 };
    char buf[1024];

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf, fmt, ap);
    va_end(ap);
    if (strcmp(lastbuf, buf))
    {
        //temp for plugin debug
        fprintf(stderr,"(theSystem)");
        vfprintf(stderr, fmt, ap);
        if (receiver){
            receiver->sys_mesg(buf);
            strcpy(lastbuf, buf);
        }
    }
}

void qSystem::debug(const char *fmt, ...)
{
    static char lastbuf[1024] = { 0 };
    char buf[1024];

    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf, fmt, ap);
    va_end(ap);
    if (strcmp(lastbuf, buf))
    {
        //temp for plugin debug
        fprintf(stderr,"(theSystem)");
        vfprintf(stderr, fmt, ap);
        if (receiver){
            receiver->sys_mesg(buf);
            strcpy(lastbuf, buf);
        }
    }
}

void qSystem::set_receiver(mainWgt* m)
{
    receiver = m;
}

const char *qSystem::httpFetch( const char *url )
{
    qDebug("qSystem::httpFetch for %s", url);
    const char *cq =  resourceIoList->checkQueued(url, qnpi);
    char *ret = 0;
    //Doc::filename() wants to free(ret), so use malloc
    if (cq) {
        ret = (char *)malloc(::strlen(cq) +1);
        ::strcpy(ret, cq);
    }
    qDebug("httpFetch returning %s", ret); 
    return (const char *)ret;
}

void qSystem::setResourceNotify(int nUrls, char** url, Doc* relative, VrmlNode *ptr)
{
    for (int i=0; i<nUrls; ++i)	{
        Doc ldoc(url[i], relative);
        resourceIoList->setClient( ldoc.url() , ptr);
    }
}

