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

int lib_gc(lua_State *L)
{
	PixelMap *p = (PixelMap *)luaL_checkudata(L,1,"PixelMap");
	if (p->surf) {
		SDL_UnlockSurface(p->surf->surf);
		p->surf = NULL;
	}
	return 0;
}

int lib_getColorIndex(lua_State *L)
{
	PixelMap *p = (PixelMap *)luaL_checkudata(L,1,"PixelMap");
	if (!p->surf) // Ignore if finalize was called.
		return 0;
	assert(p->surf->surf->format->BytesPerPixel == 1); // TODO: support 3 bpp images
	double scale = SCREENSCALE/p->surf->detail;
	int x = (p->x+luaL_optint(L,2,0)*scale);
	int y = (p->y+luaL_optint(L,3,0)*scale);
	if (x < 0 || y < 0 || x > p->surf->surf->w || y > p->surf->surf->h) // Ignore if off the edge of the image
		return 0;
	lua_pushinteger(L,((Uint8*)p->surf->surf->pixels)[x+y*p->surf->surf->pitch]);
	return 1;
}

int lib_getRGB(lua_State *L)
{
	PixelMap *p = (PixelMap *)luaL_checkudata(L,1,"PixelMap");
	if (!p->surf)
		return 0;
	int index = luaL_checkint(L,2);
	assert(p->surf->surf->format->palette != NULL); // TODO: Return RGB values, etc.
	SDL_Color color = p->surf->surf->format->palette->colors[index];
	lua_pushinteger(L,(color.r<<16)|(color.g<<8)|color.b);
	return 1;
}

static luaL_Reg lib[] = {
	{"__gc",lib_gc},
	{"finish",lib_gc},
	{"getColorIndex",lib_getColorIndex},
	{"getRGB",lib_getRGB},
	// TODO: setColorIndex
	{NULL,NULL}
};

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