#include <stdio.h>
#ifdef MSDOS
#include <conio.h>
#include <dir.h>
#include <dos.h>
#include <io.h>
#endif
#include "global.h"
#include "session.h"
#include "config.h"
#include "commands.h"
#include "timer.h"

#ifdef SCREENSAVER
extern unsigned char SCREENwidth, SCREENlength;
int32 LastIO, ScreenSaver;
static int line, state, delayit, statline;

int dossaver __ARGS((int argc,char *argv[],void *p));
extern void statLineToggle __ARGS((void));
void setscreens __ARGS((int back, int fore, int clr));

#if defined(TNOS_68K) || defined(UNIX)
#undef tputs
#include <curses.h>
static WINDOW *saved;
extern short UseCurses;
#ifdef TNOS_68K
extern chtype MY_NORMAL;
#endif
#endif

#define DELAYVAL 2

void
screensaver ()
{
	if (!ScreenSaver)
		return;
#ifdef TNOS_68K
	if (!UseCurses)
		return;
#endif
	if (secclock() > (LastIO + ScreenSaver))	{
		if (!state)	{
			statline = Current->screen->statline;
			if (statline)
				statLineToggle ();
			state = 1;
			swapscreen (Current, NULLSESSION);
#if defined(TNOS_68K) || defined(UNIX)
			saved = newwin (24, 80, 0, 0);
#ifdef TNOS_68K
			wattrset (saved, MY_NORMAL);
#endif
			leaveok (saved, 1);
#else
			_setcursortype (_NOCURSOR);
#endif
			line = delayit = 0;
		}
		if (!delayit++)	{
#if !defined(TNOS_68K) || !defined(UNIX)
			setscreens (0, 7, 1);
			gotoxy (12, ++line);
			line %= SCREENlength;
			printf (" TNOS Screen Saver Active... Press any key to continue ");
			fflush (stdout);
#else
			werase (saved);
			wmove (saved, line++, 12);
			line %= SCREENlength;
			waddstr (saved, " TNOS Screen Saver Active... Press any key to continue ");
			wrefresh (saved);
#endif
		}
		delayit %= DELAYVAL;
	} else if (state)	{
#if defined(TNOS_68K) || defined(UNIX)
		delwin (saved);
#endif
		swapscreen (NULLSESSION, Current);
		state = 0;
#if !defined(TNOS_68K) || !defined(UNIX)
		_setcursortype (_NORMALCURSOR);
#endif
		if (statline)
			statLineToggle();
	}
}

/* set the screen saver value */
int dossaver(argc, argv, p)
int argc;
char *argv[];
void *p;
{
	LastIO = secclock();
	return setlong(&ScreenSaver,"Screen Saver delay (seconds)",argc,argv);

}

void
sskick()
{
#ifdef UNIX
extern int16 intrace;

	if (!intrace && ScreenSaver)	{
#else
	if (ScreenSaver)	{
#endif
		LastIO = secclock();
		if (state)
			screensaver();
	}
}

int
ssenabled ()
{
	return state;
}

#endif /* SCREENSAVER */

