#line 9 "debugviewer.c-nw"
#include <config.h>
#include <str.h>
#include <w3a.h>
#include <w3alib.h>

typedef struct _Assoc {
    long id; W3ADocumentInfo *b;
    struct _Assoc *next;
} *Assoc;

static Assoc assoclist = NULL;

/* store -- store an ID/Buffer combination */
static void store(W3ADocumentInfo *b, long id)
{
    Assoc h;
    new(h); h->id = id; h->b = b; h->next = assoclist; assoclist = h;
}

/* delete -- delete an ID/Buffer combination */
static void delete(long id)
{
    Assoc g, h;
    assert(assoclist);
    if (assoclist->id == id) {
        h = assoclist; assoclist = assoclist->next; dispose(h);
    } else {
        assert(h->next);
        for (h = assoclist; h->next->id != id; h = h->next) assert(h->next);
        g = h->next; h->next = g->next; dispose(g);
    }
}

/* find -- find the Buffer associated with an ID */
static W3ADocumentInfo *find(long id)
{
    Assoc h;
    assert(assoclist);
    for (h = assoclist; h->id != id; h = h->next) assert(h->next);
    return h->b;
}



/* initDebug -- initialize the Debug viewer class */
EXPORT Bool initDebug(char ***mime_types, int *nrtypes, float **prefs)
{
    static char *types[] = {"*/*"};
    static float pref[] = {0.1};

    *mime_types = types;
    *nrtypes = 1;
    *prefs = pref;
    return TRUE;
}


/* openDebug -- start a new Debug viewer */
EXPORT Bool openDebug(const W3ADocumentInfo doc, W3AWindow window, long id)
{
#   define EMPTY(s) ((s) ? (s) : "")
    W3ADocumentInfo *d;

    d = new_doc();
    store(d, id);
    copy_doc(d, doc);
    debug("debug: opened viewer %ld\n", (long) d);
    debug("debug: URL = %s\n", EMPTY(doc.url));
    debug("debug: type = %s %s\n",
          EMPTY(doc.mime_type), EMPTY(doc.mime_params));
    debug("debug: size = %ld\n", doc.size);
    debug("debug: status = %s\n", EMPTY(doc.status));
    debug("debug: referer = %s\n", EMPTY(doc.referer));
    return TRUE;
}


/* writeDebug -- receive data */
EXPORT int writeDebug(long id, const char *buf, size_t nbytes)
{
    debug("debug: viewer %ld received %ld bytes\n", id, nbytes);
    return nbytes;
}


/* closeDebug -- close a Debug viewer */
EXPORT Bool closeDebug(long id)
{
    W3ADocumentInfo *d = find(id);

    dispose_doc(d);
    return TRUE;
}


/* eventDebug -- react to events happening elsewhere */
/* ARGSUSED */
EXPORT void eventDebug(long id, long source, long eventtype, void *params)
{
    /* Doesn't handle events */
}


/* infoDebug -- a chance to modify the document info based on the contents */
/* ARGSUSED */
EXPORT Bool infoDebug(long id, W3ADocumentInfo *doc)
{
    /* No modifications */
    return TRUE;
}