// $Id: kundo.cpp,v 1.8 2002/03/28 18:37:14 tokoe Exp $

#include <kdebug.h>
#include "kundo.h"

KUndo::KUndo(int maxsize_)
{
    maxsize = maxsize_;
    infront = behind = 0;

    undoList.setAutoDelete(true);
}

KUndo::~KUndo()
{
}

void KUndo::record(KUndoData *d)
{
    KUndoData *t;

    for (t = undoList.next(); t != 0; t = undoList.next())
	undoList.remove();

    undoList.append(d);
    behind++;

    checksize();
}

KUndoData *KUndo::undo()
{
    if (!canUndo())
	return 0;

    behind--;
    infront++;

    return undoList.prev();
}

KUndoData *KUndo::redo()
{
    if (!canRedo())
	return 0;

    behind++;
    infront--;

    return undoList.next();
}

void KUndo::clear()
{
    while (undoList.removeFirst());
}

bool KUndo::canUndo()
{
    if (behind > 0)
	return true;
    else
	return false;
}

bool KUndo::canRedo()
{
    if (infront < 0)
	return true;
    else
	return false;
}

void KUndo::setMaxSize(int maxsize_)
{
    maxsize = maxsize_;
    checksize();
}

int KUndo::maxSize()
{
    return maxsize;
}

void KUndo::checksize()
{
    kdDebug(4400) << "KUndo::checksize()" << endl;

    if (infront+behind > maxsize)
    {
	if (behind > 0)
	{
	    undoList.removeFirst();
	    behind--;
	}
	else if (infront > 0)
	{
	    undoList.removeLast();
	    infront--;
	}
    }
}
