#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/extensions/shape.h>
#include <X11/xpm.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "asppp.h"

extern XpmIcon *current, *Dial, *HUP, *Exit;

extern int wharfShape, ppp, chppp;
extern Display *dpy;
extern GC aspppGC;
extern Widget mainWindow;
extern XtAppContext asppp;

/* event handlers */
void ExposureHandler(Widget W, XtPointer P, XEvent *E)
{
        windowRedraw();
}

void ButtonHandler(Widget W, XtPointer P, XEvent *E)
{
	if (E->xbutton.button == 1)
	{
		if ((current->exec_name != NULL) && (current->exec_flag == 0))
		{
			system(current->exec_name);
		} else {
			exit(0);
		}
	}

	if (E->xbutton.button == 3)
		current = (XpmIcon *) current->next_xpm;
        
	windowRedraw();
}

void UpdatePPP (XtPointer P, XtIntervalId *I)
{
	ppp = pppcheck();

	if (ppp)
	{
		current = HUP;
		if (wharfShape)
		{
			(XpmIcon *) HUP->next_xpm = HUP;
		} else {
			(XpmIcon *) HUP->next_xpm = Exit;
			(XpmIcon *) Exit->next_xpm = HUP;
		}
	} else {
		current = Dial;
		if (wharfShape)
		{
			(XpmIcon *) Dial->next_xpm = Dial;
		} else {
			(XpmIcon *) Dial->next_xpm = Exit;
			(XpmIcon *) Exit->next_xpm = Dial;
		}
	}

	windowRedraw();

	XtAppAddTimeOut(asppp, chppp * 1000, (XtTimerCallbackProc)UpdatePPP, NULL);
}



/* window redraw */
void windowRedraw (void)
{
	XShapeCombineMask (dpy, XtWindow(mainWindow), ShapeBounding, 0, 0,
		current->mask, ShapeSet);
	XCopyArea (dpy, current->pixmap, XtWindow(mainWindow), aspppGC, 0, 0,
		current->attributes.width, current->attributes.height, 0, 0);
}
