/*
** 1998-05-23 -	A big fat error handling module. There are *so* many possible errors,
**		I think we really must get a grip on that situation. This is it.
**		As far as grips go, I consider this to be pretty loose. :(
*/

#include "gentoo.h"

#include <ctype.h>
#include <stdarg.h>
#include <string.h>

#include "dirpane.h"
#include "errors.h"

/* ----------------------------------------------------------------------------------------- */

#define	ERR_MAX	(1024)

/* ----------------------------------------------------------------------------------------- */

static char	edesc[ERR_MAX];

/* ----------------------------------------------------------------------------------------- */

void err_clear(MainInfo *min)
{
	edesc[0] = '\0';
	errno = 0;
}

/* 1999-01-21 -	Format an arbitrary string and print it on the status (error) line.
** BUG BUG BUG	If the formatted message exceeds 1024 bytes in length, you lose.
** UGLY   UGLY	Uses a sneaky little loop to ensure that the text is displayed *NOW*.
*/
void err_printf(MainInfo *min, char *fmt, ...)
{
	va_list	al;

	va_start(al, fmt);
	vsprintf(edesc, fmt, al);
	va_end(al);
	err_show(min);
	while(gtk_events_pending())		/* This might qualify as a kludge. */
		gtk_main_iteration();
}

/* 1998-05-30 -	Added special treatment of code == -1; this means that there is no
**		errno-compatible error information available, and the entire thing
**		is then suppressed.
*/
int err_set(MainInfo *min, gint code, const gchar *source, const gchar *obj)
{
	gint	sf;
	gint	old_errno = errno;

	if(source != NULL)
	{
		sf = toupper((int) source[0]);
		if(code >= 0)
		{
			char	*desc;

			desc = strerror(code);
			if(obj != NULL)
				g_snprintf(edesc, sizeof edesc, "%c%s on \"%s\" failed: %s (code %d)", sf, source + 1, obj, desc, code);
			else
				g_snprintf(edesc, sizeof edesc, "%c%s failed: %s (code %d)", sf, source + 1, desc, code);
		}
		else
		{
			if(obj != NULL)
				g_snprintf(edesc, sizeof edesc, "%c%s on \"%s\" failed", sf, source + 1, obj);
			else
				g_snprintf(edesc, sizeof edesc, "%c%s failed", sf, source + 1);
		}
	}
	errno = old_errno;
	return 1;
}

void err_show(MainInfo *min)
{
	if(edesc[0])
		gtk_label_set_text(GTK_LABEL(min->gui->top), edesc);
	else
		dp_show_stats(min->gui->cur_dir);
}
