#include "qe3.h"

actioninfo_t	*action_list;
actioninfo_t	*last_action;

void Undo_Init (void)
{
	action_list = malloc (sizeof (actioninfo_t));

	action_list->prev		= NULL;
	action_list->type		= -1;
	action_list->oldbrush	= NULL;
	action_list->newbrush	= NULL;
	last_action				= action_list;
}

actioninfo_t *Undo_AllocAction (int type, brush_t *oldbrush, brush_t *newbrush, int count)
{
	actioninfo_t	*action;

	action = malloc (sizeof(actioninfo_t));

	if (!action)
		Error ("Undo_AllocAction Failed!");

	action->type		= type;
	action->count		= count;
	action->oldbrush	= oldbrush;
	action->newbrush	= newbrush;

	return action;
}

void Undo_NewAction (int type, brush_t *oldbrush, brush_t *newbrush, int count)
{
	actioninfo_t	*action;

	// figure out what to do based on action type
	switch (type)
	{
	case ACTN_CUT:
		// copy selected brush and store in action->oldbrush
		// action->newbrush = modified selected brush
		break;
	case ACTN_DEL:
		action = last_action;
		if (action == action_list)
			return;
		last_action = action->prev;
//		free(action);
		action = last_action;
		break;
	case ACTN_PUT:
		action			= Undo_AllocAction (type, oldbrush, newbrush, count);
		action->prev	= last_action;
		last_action		= action;
		break;
	default:
		Error ("Invalid undo action");
	}	

	Sys_UpdateWindows (W_ALL);
}

void Undo_UndoAction (void)
{
	actioninfo_t	*action, *temp;
	int				i, count;
	
	temp = action = last_action;

	if (action == action_list)
		return;

	count = action->count;

	// restore old brush state (based on action type)
	switch (action->type)
	{
	case ACTN_CUT:
		// remove action->newbrush (selected brush)
		// select action->oldbrush
		break;
	case ACTN_DEL:
		// restore action->oldbrush and add to brush list
		// do nothing with action->newbrush because there isn't one
		break;
	case ACTN_PUT:
		// delete currently selected brushes
//		Select_Delete ();
//		// deselect currently selected brushes
		Select_Deselect ();
		// set last_action back <count> brushes
		for (i = 0; i < count; i++)
		{
			Select_Brush (action->oldbrush);
			last_action = action->prev;
//			free(action);
			action = last_action;

			if (temp == action_list)
				return;
		}

//		Select_Delete ();

		break;
	default:
		Error ("Invalid undo action");
	}

	Sys_UpdateWindows (W_ALL);

	// move the last_action to the previous action and free this one
//	last_action = action->prev;
//	free(action);
}

