#include <pspkernel.h>
#include <pspdebug.h>
#include <pspsdk.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pspdisplay.h>
#include <oslib/oslib.h>
#include "share.h"
extern tocolor(lua_State *L,int a);
extern *toImage(lua_State *L, int arg);
intraFont* font;
static int print(lua_State *L)
{
	/*if (lua_type(L, 1) == LUA_TUSERDATA){
		OSL_IMAGE *temp;
	    OSL_IMAGE *oldDrawBuf;
		temp = *toImage(L, 1);
		oslUnswizzleImage(temp);
		oldDrawBuf = oslGetDrawBuffer();
		oslMoveImageTo(temp, OSL_IN_VRAM);
		oslSetDrawBuffer(temp);
		intraFontSetStyle(font, luaL_checknumber(L,5),toColor(L,6),toColor(L,7),INTRAFONT_ALIGN_LEFT);
		lua_pushnumber(L, intraFontPrint(font,luaL_checknumber(L,2), (luaL_checknumber(L,3)-1), luaL_checkstring(L,4)));
		oslSetDrawBuffer(oldDrawBuf);
		oslMoveImageTo(temp, OSL_IN_RAM);
		oslSwizzleImage(temp);
		return 1;
	}*/
 //oslIntraFontSetStyle(font, luaL_checknumber(L,4),toColor(L,5),toColor(L,6),INTRAFONT_ALIGN_LEFT);
 intraFontSetStyle(font, luaL_checknumber(L,4),tocolor(L,5),tocolor(L,5),INTRAFONT_ALIGN_LEFT);
 //oslDrawString(luaL_checknumber(L,1), (luaL_checknumber(L,2)-1), luaL_checkstring(L,3));
 lua_pushnumber(L, intraFontPrint(font,luaL_checknumber(L,1), (luaL_checknumber(L,2)-1), luaL_checkstring(L,3)));
 return 1;
}
static int startDraw(lua_State *L)
{
 oslStartDrawing();
 return 0;
}
static int endDraw(lua_State *L)
{
 oslEndDrawing();
 return 0;
}
static int flipscreen(lua_State *L)
{
 //oslSwapBuffers();
 //sceGuSwapBuffers();
 oslEndFrame();
 oslSyncFrame();
 return 0;
}
static int clear(lua_State *L)
{
 oslClearScreen(tocolor(L,1));
 return 0;
}
static int screen_transparent (lua_State *L){
	oslSetTransparentColor(tocolor(L,1));
	return 0;
}
static int screen_toImage (lua_State *L) {
	OSL_IMAGE* image = oslCreateImageCopy(OSL_SECONDARY_BUFFER, OSL_IN_RAM);
	OSL_IMAGE** luaImage = pushImage(L);
	*luaImage = image;
	return 1;
}
static int screen_waitVblankStart (lua_State *L){
	if(lua_gettop(L)==1){
		int i;
		for (i = 1; i < luaL_checknumber(L,1); ++i){
			sceDisplayWaitVblankStart();
		}
	}else{
		sceDisplayWaitVblankStart();
	}
	return 0;
}
static int screen_alpha (lua_State *L){
	oslSetAlpha(OSL_FX_ALPHA, luaL_checknumber(L,1));
	return 0;
}
static const luaL_Reg screen[] = {
  {"print",   print},
  {"startDraw",   startDraw},
  {"endDraw",   endDraw},
  {"flipscreen",   flipscreen},
  {"clear",   clear},
  {"waitVblankStart",	screen_waitVblankStart},
  {"toImage", 	screen_toImage},
  {"transparentColor", 	screen_transparent},
  {"setAlpha", 	screen_alpha},
  {NULL, NULL}
};
static void initscreen(void){
	intraFontInit();
	//font = oslLoadFontFile("flash0:/font/ltn0.pgf");
	font = intraFontLoad("flash0:/font/ltn0.pgf",INTRAFONT_CACHE_ALL | INTRAFONT_STRING_UTF8);
	intraFontActivate(font);
	//oslSetFont(font);
	//guSwapBuffersBehaviour(PSP_DISPLAY_SETBUF_IMMEDIATE);
}
void screen_init(lua_State *L) {
	initscreen();
	luaL_register(L, "screen", screen);
}


