#include "main.h"
#include <lua.h>
#include <lauxlib.h>
#include "gfx.h"
#include "lib_surface.h"

static int lib_load(lua_State *L)
{
	const char *name = luaL_checkstring(L,1);
	lua_Number detail = luaL_optnumber(L,2,1);
	bool allow_wii = (lua_gettop(L) < 3 || lua_toboolean(L,3));
	Lua_Surface *data = lua_newuserdata(L, sizeof(Lua_Surface));
	bool wiidata;
	data->surf = Gfx_Load(name,&wiidata,allow_wii);
	if (wiidata)
		detail = 2;
	data->detail = detail;
	double scale = SCREENSCALE/detail; // detail 1 = 2x (320->640), detail 2 = 1x (640->640), detail 3 = 0.6666x (960->640), detail 4 = 0.5x (1280->640) etc.
	// Currently only detail levels which produce whole numbers can be handled.
	if (data->surf && scale > 1)
		data->surf = Gfx_Scale(data->surf,scale);
	// TODO: scale < 1
	luaL_getmetatable(L,"SDL_Surface");
	lua_setmetatable(L,-2);
	lua_pushboolean(L,wiidata);
	return 2;
}

static luaL_Reg lib[] = {
	{"load",lib_load},
	{NULL,NULL}
};

void agllib_pbm(lua_State *L)
{
	luaL_register(L,"pbm",lib);
	lua_pop(L,1);
}
