/**************************************************************************

    This file is part of Xclass95, a Win95-looking GUI toolkit.
    Copyright (C) 1996, 1997 Ricky Ralston, Hector Peraza.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

**************************************************************************/

#include <xclass/utils.h>
#include <xclass/OXSList.h>


OXSList::OXSList(Display *dpy, XPointer data)
{
    _dpy      = dpy;
    _nentries = 0;
    _head     = _tail = NULL;
    _data     = data;
    _context  = XUniqueContext();
}

OXSList::~OXSList()
{
    OXSNode *e = _head, *next;

    while (e)
    {
        next = e->next;
        XDeleteContext(_dpy, e->id, _context);
        delete e;
        e = next;
    }
}

OXSNode *OXSList::Add(int id, XPointer data)
{
    Remove(id);  // remove existing node, if any...

    OXSNode *e = new OXSNode;

    if (!e) return NULL;

    e->next = NULL;
    e->prev = NULL;
    e->id   = id;
    e->data = data;

    if (_head == NULL)
    {
        _head = _tail = e;
    }
    else
    {
        _head->prev = e;
        e->next = _head;
        _head = e;
    }

    _nentries++;
    XSaveContext(_dpy, e->id, _context, (XPointer) e);

    return e;
}

Bool OXSList::Remove(int id)
{
    OXSNode *e, *item;

    if ((XFindContext(_dpy, id, _context, (XPointer *)&item)) == XCNOENT)
        return False;

    if (item->prev == NULL)
    {
        _head = item->next;
        if (_head == NULL)
          _tail = NULL;
        else
          _head->prev = NULL;
    }
    else if (item->next == NULL)
    {
        e = item->prev;
        e->next = NULL;
        _tail = e;
    }
    else
    {
        e = item->prev;
        e->next = item->next;
        e = item->next;
        e->prev = item->prev;
    }

    XDeleteContext(_dpy, id, _context);
    delete item;
    _nentries--;

    return True;
}

OXSNode *OXSList::GetNode(int id)
{
    OXSNode *item;

    if ((XFindContext(_dpy, id, _context, (XPointer *)&item)) == XCNOENT)
        return NULL;

    return item;
}
