/* Copyright 2023 Tranquillity Codes

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// --------------
// LuaBar v0.2.0
// --------------
// Usage: <text generator> | textbar | <input handler>
//
// Shows the last two lines from stdin on a bar
// Every odd line is on the left
// Every even line is on the right
// Updating one side at a time is not possible
// Line buffered
// Prints all mouse clicks to stdout
// In the format of `X Y` (without the '`')
// Rendering handled by config.lua
// File dofile'd every render
// Called as draw(ctx, width, text_conf, text, text_other)
// Some cairo bindings provided (see below)

#include <pthread.h>

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>

#include <cairo.h>
#include <cairo-xlib.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

Display* dpy;
lua_State *lua;
Window win;
cairo_surface_t* sfc;
cairo_t* ctx;
char text[256] = {0};
char text_other[256] = {0};
char text_other2[256] = {0};
char text_conf[256] = {0};
float b_col_r = 0.157;
float b_col_g = 0.165;
float b_col_b = 0.212;
int width;


// CONFIG
#define POSITION 0 // 1 means top, 0 means bottom. Blame C.
#define FONT "Fira Code"
#define FONT_SIZE 16
#define FONT_SIZE2 16
#define BG_COLOR b_col_r, b_col_g, b_col_b, 0.950
#define FG_COLOR 0.973, 0.973, 0.949, 1.000

// COMPUTATION
#define HEIGHT FONT_SIZE*2
#define FONT_POS FONT_SIZE*1.4

#define FONT_POS2 FONT_SIZE2*1.4
//#define FONT_POS2 FONT_SIZE2*2.2/2.0

int l_cairo_set_source_rgba(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double r = lua_tonumber(L, 2);
	double g = lua_tonumber(L, 3);
	double b = lua_tonumber(L, 4);
	double a = lua_tonumber(L, 5);

	//printf("set_source_rgba(%d, %f, %f, %f, %f)\n", ctx, r, g, b, a);

	cairo_set_source_rgba(ctx, r, g, b, a);

	return 0;
}

int l_cairo_arc(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double xc = lua_tonumber(L, 2);
	double yc = lua_tonumber(L, 3);
	double r = lua_tonumber(L, 4);
	double a1 = lua_tonumber(L, 5);
	double a2 = lua_tonumber(L, 6);

	//printf("set_source_rgba(%d, %f, %f, %f, %f)\n", ctx, r, g, b, a);

	cairo_arc(ctx, xc, yc, r, a1, a2);

	return 0;
}

int l_cairo_rectangle(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double x = lua_tonumber(L, 2);
	double y = lua_tonumber(L, 3);
	double w = lua_tonumber(L, 4);
	double h = lua_tonumber(L, 5);

	//printf("set_source_rgba(%d, %f, %f, %f, %f)\n", ctx, r, g, b, a);

	cairo_rectangle(ctx, x, y, w, h);

	return 0;
}

int l_cairo_paint(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);

	//printf("paint()\n");

	cairo_paint(ctx);

	return 0;
}

int l_cairo_fill(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);

	//printf("fill()\n");

	cairo_fill(ctx);

	return 0;
}

int l_cairo_stroke(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);

	//printf("stroke()\n");

	cairo_stroke(ctx);

	return 0;
}

int l_cairo_rel_line_to(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double x = lua_tonumber(L, 2);
	double y = lua_tonumber(L, 3);

	//printf("move_to(%f, %f)\n", x, y);

	cairo_rel_line_to(ctx, x, y);

	return 0;
}


int l_cairo_move_to(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double x = lua_tonumber(L, 2);
	double y = lua_tonumber(L, 3);

	//printf("move_to(%f, %f)\n", x, y);

	cairo_move_to(ctx, x, y);

	return 0;
}

int l_cairo_select_font_face(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	char* fm = lua_tostring(L, 2);
	cairo_font_slant_t sl = lua_tonumber(L, 3);
	cairo_font_weight_t wg = lua_tonumber(L, 4);

	//printf("select_font_face(%s, %d, %d)\n", fm, sl, wg);

	cairo_select_font_face(ctx, fm, sl, wg);

	return 0;
}

int l_cairo_set_font_size(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double sz = lua_tonumber(L, 2);

	//printf("set_font_size(%f)\n", sz);

	cairo_set_font_size(ctx, sz);

	return 0;
}

int l_cairo_set_line_width(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	double wh = lua_tonumber(L, 2);

	//printf("set_line_width(%f)\n", wh);

	cairo_set_line_width(ctx, wh);

	return 0;
}

int l_cairo_show_text(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	char* txt = lua_tostring(L, 2);

	//printf("show_text(%s)\n", txt);

	cairo_show_text(ctx, txt);

	return 0;
}

int l_cairo_text_extents(lua_State *L) {
	void* ctx = (uint64_t)lua_tonumber(L, 1);
	char* txt = lua_tostring(L, 2);


	cairo_text_extents_t extents;
	cairo_text_extents(ctx, txt, &extents);

	lua_createtable(L, 0, 6);

	lua_pushstring(L, "x_bearing");
	lua_pushinteger(L, extents.x_bearing);
	lua_settable(L, -3);

	lua_pushstring(L, "y_bearing");
	lua_pushinteger(L, extents.y_bearing);
	lua_settable(L, -3);

	lua_pushstring(L, "width");
	lua_pushinteger(L, extents.width);
	lua_settable(L, -3);

	lua_pushstring(L, "height");
	lua_pushinteger(L, extents.height);
	lua_settable(L, -3);

	lua_pushstring(L, "x_advance");
	lua_pushinteger(L, extents.x_advance);
	lua_settable(L, -3);

	lua_pushstring(L, "y_advance");
	lua_pushinteger(L, extents.y_advance);
	lua_settable(L, -3);

	return 1;
}

void init() {
	dpy = XOpenDisplay(NULL);
	int screen = DefaultScreen(dpy);
	width = DisplayWidth(dpy, screen);

	XVisualInfo visualinfo;
	XMatchVisualInfo(dpy, screen, 32, TrueColor, &visualinfo);
	XSetWindowAttributes attr;
	attr.colormap = XCreateColormap(dpy, DefaultRootWindow(dpy), visualinfo.visual, AllocNone);
  attr.background_pixel = 0;
  attr.border_pixel = 0;
	win = XCreateWindow(dpy, DefaultRootWindow(dpy),
											0, 0, width, HEIGHT,
											0, visualinfo.depth, InputOutput, visualinfo.visual, CWBackPixel | CWColormap | CWBorderPixel, &attr);
	//XSetWindowBackground(dpy, win, 60369011);
	XSync(dpy, False);
	Atom wm_type = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
	long wm_type_dock = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK", False);
	XChangeProperty(dpy, win, wm_type,
			XA_ATOM, 32, PropModeReplace, (unsigned char *) &wm_type_dock, 1);

	Atom wm_strut = XInternAtom(dpy, "_NET_WM_STRUT", False);

#if POSITION == 0
	XMoveWindow(dpy, win, 0, DisplayHeight(dpy, screen));
	uint32_t strut[4] = {0, 0, 0, HEIGHT};
	XChangeProperty(dpy, win, wm_strut,
			XA_CARDINAL, 32, PropModeReplace, (unsigned char *) strut, 4);
#elif POSITION == 1
	uint32_t strut[4] = {0, 0, HEIGHT, 0};
	XChangeProperty(dpy, win, wm_strut,
			XA_CARDINAL, 32, PropModeReplace, (unsigned char *) strut, 4);
	XMoveWindow(dpy, win, 0, 0);
#endif

	XMapWindow(dpy, win);
	sfc = cairo_xlib_surface_create(dpy, win, visualinfo.visual, DisplayWidth(dpy, screen), HEIGHT);
	ctx = cairo_create(sfc);

	lua = luaL_newstate();
	luaL_openlibs(lua);

	//luaL_dofile(lua, "config.lua");

	lua_pushcfunction(lua, l_cairo_set_source_rgba);
	lua_setglobal(lua, "cairo_set_source_rgba");
	lua_pushcfunction(lua, l_cairo_paint);
	lua_setglobal(lua, "cairo_paint");
	lua_pushcfunction(lua, l_cairo_move_to);
	lua_setglobal(lua, "cairo_move_to");
	lua_pushcfunction(lua, l_cairo_select_font_face);
	lua_setglobal(lua, "cairo_select_font_face");
	lua_pushcfunction(lua, l_cairo_set_font_size);
	lua_setglobal(lua, "cairo_set_font_size");
	lua_pushcfunction(lua, l_cairo_show_text);
	lua_setglobal(lua, "cairo_show_text");
	lua_pushcfunction(lua, l_cairo_text_extents);
	lua_setglobal(lua, "cairo_text_extents");
	lua_pushcfunction(lua, l_cairo_fill);
	lua_setglobal(lua, "cairo_fill");
	lua_pushcfunction(lua, l_cairo_stroke);
	lua_setglobal(lua, "cairo_stroke");
	lua_pushcfunction(lua, l_cairo_arc);
	lua_setglobal(lua, "cairo_arc");
	lua_pushcfunction(lua, l_cairo_rectangle);
	lua_setglobal(lua, "cairo_rectangle");
	lua_pushcfunction(lua, l_cairo_set_line_width);
	lua_setglobal(lua, "cairo_set_line_width");
	lua_pushcfunction(lua, l_cairo_rel_line_to);
	lua_setglobal(lua, "cairo_rel_line_to");
}

pthread_mutex_t do_paint;
void paint(Display* dpy) {
	if(!pthread_mutex_lock(&do_paint)) {

		cairo_push_group(ctx);

		cairo_set_source_rgba(ctx, 0.0, 0.0, 0.0, 0.0);

	  cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
	  cairo_paint(ctx);

		cairo_set_operator(ctx, CAIRO_OPERATOR_OVER);

		luaL_dofile(lua, "config.lua");

		lua_getglobal(lua, "draw");
		lua_pushinteger(lua, ctx);
		lua_pushinteger(lua, width);
		lua_pushstring(lua, text_conf);
		lua_pushstring(lua, text);
		lua_pushstring(lua, text_other);

	  lua_pcall(lua, 5, 0, 0);
	 
		cairo_pop_group_to_source(ctx);

		cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
		cairo_paint(ctx);

		cairo_surface_flush(sfc);
		XFlush(dpy);

		pthread_mutex_unlock(&do_paint);
	}
}

void update() {
	while(1) {
		fgets(text, 256, stdin);
		fgets(text_other, 256, stdin);
		fgets(text_other2, 256, stdin);
		fgets(text_conf, 256, stdin);

		text[strcspn(text, "\n")] = 0;
		text_other[strcspn(text_other, "\n")] = 0;
		text_other2[strcspn(text_other2, "\n")] = 0;
		text_conf[strcspn(text_conf, "\n")] = 0;

		paint(dpy);
	}
}

void x_loop() {
	Display* x_dpy = XOpenDisplay(NULL);
	XSelectInput(x_dpy, win, ButtonPressMask | StructureNotifyMask | ExposureMask);
	while(1) {
		XEvent e;
		XNextEvent(x_dpy, &e);
		if(e.type == ButtonPress && e.xbutton.button == Button1) {
			printf("%d %d\n", e.xbutton.x, e.xbutton.y);
			fflush(stdout);
		} else if(e.type == ConfigureNotify) {
			cairo_xlib_surface_set_size(sfc, e.xconfigure.width, e.xconfigure.height);
		} else
		if(e.type == Expose) {
			//fprintf(stderr, "expose\n");
			paint(x_dpy);
		}
	}
}

int main() {
	init();
	paint(dpy);

	pthread_mutex_init(&do_paint, NULL);
	pthread_t x_thread_id;
	pthread_create(&x_thread_id, NULL, &x_loop, NULL);

	update();
}
