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

static int lib_gc(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	if (s->surf)
		SDL_FreeSurface(s->surf);
	s->surf = NULL;
	return 0;
}

static int lib_width(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	// This returns the same number for textures of all detail levels,
	// accounting both for its scale and its resolution.
	// i.e. a 256 pixel wide texture with a detail of 1
	// is equivilant to a 512 pixel wide texture with a detail of 2
	// and both of them return 256 even though they are both 512 in memory.
	// TODO: Optimize mah crazy maths here...
	double scale = SCREENSCALE/s->detail;
	lua_pushinteger(L,s->surf->w/scale/s->detail);
	return 1;
}

static int lib_height(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	double scale = SCREENSCALE/s->detail;
	lua_pushinteger(L,s->surf->h/scale/s->detail);
	return 1;
}

static int lib_detail(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	lua_pushinteger(L,s->detail);
	return 1;
}

static int lib_pixelmap(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	PixelMap *p = lua_newuserdata(L,sizeof(PixelMap));
	memset(p,0,sizeof(PixelMap));
	p->surf = s;
	p->x = luaL_optnumber(L,2,0)*(double)SCREENSCALE;
	p->y = luaL_optnumber(L,3,0)*(double)SCREENSCALE;
	SDL_LockSurface(s->surf);
	luaL_getmetatable(L,"PixelMap");
	lua_setmetatable(L,-2);
	return 1;
}

static int lib_setColorIndex(lua_State *L)
{
	Lua_Surface *s = luaL_checkudata(L,1,"SDL_Surface");
	int index = luaL_optint(L,2,1);
	int color = luaL_optint(L,3,0);
	assert(s->surf->format->palette != NULL);
	if (index > s->surf->format->palette->ncolors)
		return 0;
	SDL_Color rgb = {(color>>16)&0xFF,(color>>8)&0xFF,color&0xFF,0x00};
	SDL_SetColors(s->surf,&rgb,index,1);
	return 0;
}

static luaL_Reg lib[] = {
	{"__gc",lib_gc},
	{"w",lib_width},
	{"h",lib_height},
	{"detail",lib_detail},
	{"getPixels",lib_pixelmap},
	{"setColorIndex",lib_setColorIndex},
	{NULL,NULL}
};

void agllib_surface(lua_State *L)
{
	luaL_newmetatable(L,"SDL_Surface");
	lua_pushvalue(L,-1);
	lua_setfield(L,-2,"__index");
	luaL_register(L,NULL,lib);
	lua_pop(L,1);

}
