/*
 * Set user automatically to away or n/a mode after designated # of idle
 * minutes.
 * Originally written by Jeremy Wise <jwise@pathwaynet.com>
 * Modified by suggestion of John Rapp <jlrapp@ucsd.edu>
 */

#include "gtkicq.h"
#include "gtkfunc.h"

#ifdef USE_XSCREENSAVER
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>

int old_status = -1;

void auto_away( struct sokandlb *data )
{
	static Display *display = NULL;
	int time_idle;
	static XScreenSaverInfo *info = NULL;

#ifdef TRACE_FUNCTION
	printf( "auto_away\n" );
#endif

	if( !display )
		display = XOpenDisplay( getenv( "DISPLAY" ) );
	
	if( Current_Status != STATUS_ONLINE && Current_Status != STATUS_AWAY &&
	    Current_Status != STATUS_FREE_CHAT && Current_Status != STATUS_NA )
		return;

	if( !info )
		info = XScreenSaverAllocInfo();
	XScreenSaverQueryInfo ( display, DefaultRootWindow( display ),
	                        info );

	time_idle = info->idle;

	if( time_idle > 60000 * AUTO_NA && Current_Status != STATUS_NA )
	{
		if( old_status == -1 )
			old_status = Current_Status;
		icq_change_status( data->sok, STATUS_NA, data );
	}
	else if( time_idle > 60000 * AUTO_AWAY && Current_Status != STATUS_AWAY )
	{
		if( old_status == -1 )
			old_status = Current_Status;
		icq_change_status( data->sok, STATUS_AWAY, data );
	}
	else
	{
		if( old_status != -1 )
			icq_change_status( data->sok, old_status, data );
		old_status = -1;
	}
}

#endif
