/*
 * 	File sfile.c
 */

#include <stdio.h>
#include <string.h>

#include "mgui.h"

void CloseDialogCB(MOBJECT p, void *s, void *v);

extern MTColor black, white, cadetblue, seagreen;

MOBJECT fname_label;

/**************************************************
 *	Callback that prints the currently viewed file
 **************************************************/
void PrintFileCB(MOBJECT p, void *s, void *adata)
{
	MOBJECT label = (MOBJECT )adata;
	char fname[128];
	char str[256];
	int ret;
/*
 * Get the file name from the label that holds it
 */
	MObjectGetText(label, fname);
	sprintf(str, "Print file:\n%s", fname);
	if (MMessageDialog("", str, "Exec", "Cancel", NULL))
		return;
/*
 * Cycle while the printer is not ready and the user
 * chooses to retry
 */
	do {
		ret = MSpoolFile(fname);
	} while (ret == MSPOOL_NOT_READY &&
		MMessageDialog("Warning",
			"The printer is not ready",
			"Retry", "Abort", NULL) == 0);
	switch (ret) {
		case MSPOOL_OK:
			MMessageDialog("", "Print Job Started!", "Ok", NULL);
			break;
		case MSPOOL_FULL_QUEUE:
			MMessageDialog("", "Print Queue is FULL!", "Ok", NULL);
			break;
		case MSPOOL_FILE_ERR:
			MMessageDialog("ERROR", fname, "Ok", NULL);
			break;
	}
}

/**************************************************
 *	This callback is used to change the file
 **************************************************/
void NewFileCB(MOBJECT p, void *s, void *adata)
{
	MOBJECT sfile = (MOBJECT )adata;
	char fname[128], dirname[128];
#ifdef UNIX
#define FILTER	"*"
#else
#define FILTER	"*.*"
#endif

	dirname[0] = '\0';
	fname[0] = '\0';
	if (MFileSelection("File Selection Box", FILTER, fname, dirname, True)) {
		strcat(dirname, fname);
		MObjectSetText(fname_label, dirname);
		MSFileSetFile(sfile, dirname);
	}
}

/*****************************************************
 *	This callback opens the dialog when the
 *	corresponding menu item is selected
 *****************************************************/
void SFileCB(MOBJECT o, void *o_data, void *a_data)
{
	MOBJECT pbutton, shell, form, sfile;

	shell = MCreateShell("Scrolled File", SF_MODAL);

	fname_label = MCreateLabel(shell, __FILE__, DEFAULT_FONT);

	sfile = MCreateSFile(shell, __FILE__, DEFAULT_FONT, 15, 70);
	MObjectSetColor(sfile, seagreen, black);
	MSBLSetHMargin(sfile, 0);

	form = MCreateColForm(shell);

	pbutton = MCreatePButton(form, "New", TIMES_L_FONT);
	MPButtonSetCallback(pbutton, NewFileCB, sfile);

	pbutton = MCreatePButton(form, "Print", TIMES_L_FONT);
	MPButtonSetCallback(pbutton, PrintFileCB, fname_label);

	pbutton = MCreatePButton(form, "Close", TIMES_L_FONT);
	MPButtonSetCallback(pbutton, CloseDialogCB, 0L);

	MShellRealize(shell);
}
