/* 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.
*/

// --------------
// TextBar v0.1.2
// --------------
// 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 '`')

#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>

Display* dpy;
Window win;
cairo_surface_t* sfc;
cairo_surface_t* sfc2;
cairo_t* ctx;
cairo_t* ctx2;
char text[256] = {0};
char text_other[256] = {0};
int width;


// CONFIG
#define POSITION 0 // 1 means top, 0 means bottom. Blame C.
#define FONT "Fira Code"
#define FONT_SIZE 16
#define BG_COLOR 0.157, 0.165, 0.212, 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

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);
	sfc2 = cairo_surface_create_similar(sfc, CAIRO_CONTENT_COLOR_ALPHA, DisplayWidth(dpy, screen), HEIGHT);
	ctx = cairo_create(sfc);
	ctx2 = cairo_create(sfc2);
}

pthread_mutex_t do_paint;
void paint(Display* dpy) {
	if(!pthread_mutex_lock(&do_paint)) {
		// Clear
		cairo_set_source_rgba(ctx2, 0.0, 0.0, 0.0, 0.0);
		cairo_set_operator(ctx2, CAIRO_OPERATOR_SOURCE);
		cairo_paint(ctx2);
		cairo_set_operator(ctx2, CAIRO_OPERATOR_OVER);

		// Background
		cairo_set_source_rgba(ctx2, BG_COLOR);
		cairo_paint(ctx2);

		// Left text
		cairo_move_to(ctx2, FONT_SIZE / 2, FONT_POS);
		cairo_select_font_face(ctx2, FONT, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
		cairo_set_font_size(ctx2, FONT_SIZE);
		cairo_set_source_rgba(ctx2, FG_COLOR);
		cairo_show_text(ctx2, text);

		// Right text
		cairo_text_extents_t extents;
		cairo_text_extents(ctx2, text_other, &extents);
		cairo_move_to(ctx2, (width-extents.width) - FONT_SIZE / 2, FONT_POS);
		cairo_show_text(ctx2, text_other);

		// Backbuffer -> Frontbuffer
		cairo_set_source_surface(ctx, sfc2, 0, 0);
		cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
		cairo_paint(ctx);

		// Flushing
		cairo_surface_flush(sfc);
		XFlush(dpy);

		pthread_mutex_unlock(&do_paint);
	}
}

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

		text[strcspn(text, "\n")] = 0;
		text_other[strcspn(text_other, "\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) {
			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();
}
