/*************************************
**
**Power.c
**
***************************************/
#define MWINCLUDECOLORS

#include "nano-X.h"
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>


#define SCREEN_WIDTH 600     
#define SCREEN_HEIGHT 800

#define CM_SW_OFF	110
#define CM_PWR		112

GR_WINDOW_ID wid;

GR_GC_ID gc;

GR_FONT_ID font;

/***********************************************************
		function :Power_off
*============================================================
**	Description:power off 
**	param :no
**	return  0
****************************************************************/
int Power_off()
{
	int value = 0;
	int fpid = open("/dev/pvi_ioc",O_RDONLY|O_NONBLOCK);
	ioctl(fpid,CM_SW_OFF,&value);
	if(value == 0){
		GrClearArea(wid,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0);
		GrText(wid,gc,50,350,"GoodBye",-1,GR_TFASCII);
		GrShowWindow(wid,gc,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
		
		GrClearArea(wid,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0);
		GrShowWindow(wid,gc,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
		GrClearArea(wid,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0);
		GrShowWindow(wid,gc,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
		
		GrDestroyFont(font);
		GrDestroyWindow(wid);
		GrDestroyGC(gc);
		GrClose();
		ioctl(fpid,CM_PWR,0);
		close(fpid);
		system("reboot");
		return 0;
	}
	else close(fpid);
	return 1;
}

/*************************************************************************
**			Function:event_handler
**=========================================================================
**
**	Description:responding the event which select by GrSelectEvents()
**	param : event
**	return : 0
****************************************************************************/

int event_handler(GR_EVENT *event)
{	
	switch(event->type)
	{
		case GR_EVENT_TYPE_EXPOSURE:		
			GrClearArea(wid,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0);
			GrText(wid,gc,50,350,"Hello",-1,GR_TFASCII);
			GrShowWindow(wid,gc,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
		break;
		
		case GR_EVENT_TYPE_CLOSE_REQ:
			GrDestroyFont(font);	
			GrDestroyWindow(wid);
			GrDestroyGC(gc);
			GrClose();
			exit (0);
		break;
		
		default:
		break;
	}
	return 0;
}

int main(void)
{
	GR_EVENT event;
	
	if (GrOpen() < 0) {
       		fprintf (stderr, "GrOpen failed");
        	return 1;
	}
	wid = GrNewWindowEx(GR_WM_PROPS_APPWINDOW,NULL,GR_ROOT_WINDOW_ID, 0, 0, SCREEN_WIDTH,SCREEN_HEIGHT,WHITE);
	GrSelectEvents(wid, GR_EVENT_MASK_CLOSE_REQ | GR_EVENT_MASK_EXPOSURE);
	GrMapWindow(wid);
	gc = GrNewGC();
	font = GrCreateFont("mfont.mbf",0, NULL);
	GrSetFontSize(font,36);
	GrSetGCFont(gc,font);
	GrSetGCUseBackground(gc, GR_TRUE);
	GrSetGCForeground(gc,BLACK);
	GrSetGCBackground(gc,WHITE);
	while(1){
		GrCheckNextEvent(&event);
		event_handler(&event);
		Power_off();
	}	
	return 0;
}