#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"

/* Media transport controls: play and pause, previous and next, a seek bar
 * with the time on either side, volume and full screen, in one row. The
 * app plays; this only shows where it is and says what the user asked. */

#define HEIGHT 56
#define BUTTON 40
#define RING 2
#define GAP 6
#define TRACK_H 4
#define THUMB_W 8
#define THUMB_H 24
#define VOLUME_W 90
#define TIME_W 52
#define SEEK_STEP 5.0
#define VOLUME_STEP 0.05
#define NARROW_VOLUME 560 // below this width the volume slider goes
#define NARROW_TIME 340 // and below this the times

enum zone {
	ZONE_NONE = -1,
	ZONE_PREV,
	ZONE_PLAY,
	ZONE_NEXT,
	ZONE_SEEK,
	ZONE_MUTE,
	ZONE_VOLUME,
	ZONE_FULL,
	ZONE_COUNT,
};

struct transport {
	c8ui_transport_fn fn;
	void *data;
	bool playing, muted, fullscreen;
	bool show_skip, show_full;
	double position, duration, buffered; // seconds, seconds, 0 to 1
	double volume;
	enum zone hover, drag;
	bool live; // the seek or volume is being dragged
	double drag_value; // while dragging
	double *marks; // seconds: chapters, cut into the seek bar
	int mark_count;
};

static void zones(struct c8ui_widget *w, struct c8ui_rect z[ZONE_COUNT]) {
	struct transport *t = w->data;
	double x = w->rect.x, y = w->rect.y + (HEIGHT - BUTTON) / 2.0;
	double right = w->rect.x + w->rect.width;
	memset(z, 0, sizeof(struct c8ui_rect) * ZONE_COUNT);
	if (t->show_skip) {
		z[ZONE_PREV] = (struct c8ui_rect){ x, y, BUTTON, BUTTON };
		x += BUTTON + GAP;
	}
	z[ZONE_PLAY] = (struct c8ui_rect){ x, y, BUTTON, BUTTON };
	x += BUTTON + GAP;
	if (t->show_skip) {
		z[ZONE_NEXT] = (struct c8ui_rect){ x, y, BUTTON, BUTTON };
		x += BUTTON + GAP;
	}
	if (t->show_full) {
		z[ZONE_FULL] = (struct c8ui_rect){ right - BUTTON, y, BUTTON, BUTTON };
		right -= BUTTON + GAP;
	}
	if (w->rect.width >= NARROW_VOLUME) {
		z[ZONE_VOLUME] = (struct c8ui_rect){ right - VOLUME_W, y, VOLUME_W,
			BUTTON };
		right -= VOLUME_W + GAP;
	}
	z[ZONE_MUTE] = (struct c8ui_rect){ right - BUTTON, y, BUTTON, BUTTON };
	right -= BUTTON + GAP * 2;
	z[ZONE_SEEK] = (struct c8ui_rect){ x, y, right - x > 0 ? right - x : 0,
		BUTTON };
}

static void format_time(double seconds, char *buf, size_t len) {
	int s = seconds < 0 ? 0 : (int)seconds;
	if (s >= 3600) {
		snprintf(buf, len, "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60);
	} else {
		snprintf(buf, len, "%d:%02d", s / 60, s % 60);
	}
}

static void transport_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	*width = avail;
	*height = HEIGHT;
}

static void round_button(cairo_t *cr, struct c8ui_rect r, uint32_t fg,
		uint32_t bg, bool hot, bool down, double alpha) {
	double cx = r.x + r.width / 2, cy = r.y + r.height / 2;
	cairo_new_path(cr);
	cairo_arc(cr, cx, cy, BUTTON / 2.0 - RING / 2.0, 0, 2 * M_PI);
	if (down) {
		c8ui_set_source(cr, fg, alpha);
		cairo_fill_preserve(cr);
	} else if (hot) {
		c8ui_set_source(cr, fg, 0.15 * alpha);
		cairo_fill_preserve(cr);
	}
	c8ui_set_source(cr, fg, alpha);
	cairo_set_line_width(cr, RING);
	cairo_stroke(cr);
	(void)bg;
}

static void glyph_play(cairo_t *cr, double cx, double cy) {
	cairo_move_to(cr, cx - 5, cy - 8);
	cairo_line_to(cr, cx + 8, cy);
	cairo_line_to(cr, cx - 5, cy + 8);
	cairo_close_path(cr);
	cairo_fill(cr);
}

static void glyph_pause(cairo_t *cr, double cx, double cy) {
	cairo_rectangle(cr, cx - 6, cy - 8, 4, 16);
	cairo_rectangle(cr, cx + 2, cy - 8, 4, 16);
	cairo_fill(cr);
}

/* Previous: a bar with a triangle pointing at it; next the other way */
static void glyph_skip(cairo_t *cr, double cx, double cy, bool next) {
	double d = next ? 1 : -1;
	cairo_rectangle(cr, cx + d * 6 - 1.5, cy - 8, 3, 16);
	cairo_move_to(cr, cx - d * 6, cy - 8);
	cairo_line_to(cr, cx + d * 3, cy);
	cairo_line_to(cr, cx - d * 6, cy + 8);
	cairo_close_path(cr);
	cairo_fill(cr);
}

static void glyph_speaker(cairo_t *cr, double cx, double cy, bool muted,
		double volume) {
	cairo_move_to(cr, cx - 9, cy - 3);
	cairo_line_to(cr, cx - 5, cy - 3);
	cairo_line_to(cr, cx, cy - 8);
	cairo_line_to(cr, cx, cy + 8);
	cairo_line_to(cr, cx - 5, cy + 3);
	cairo_line_to(cr, cx - 9, cy + 3);
	cairo_close_path(cr);
	cairo_fill(cr);
	cairo_set_line_width(cr, 1.5);
	if (muted || volume <= 0) {
		cairo_move_to(cr, cx + 4, cy - 4);
		cairo_line_to(cr, cx + 10, cy + 4);
		cairo_move_to(cr, cx + 10, cy - 4);
		cairo_line_to(cr, cx + 4, cy + 4);
		cairo_stroke(cr);
		return;
	}
	cairo_new_path(cr);
	cairo_arc(cr, cx + 1, cy, 5, -M_PI / 3, M_PI / 3);
	cairo_stroke(cr);
	if (volume > 0.5) {
		cairo_new_path(cr);
		cairo_arc(cr, cx + 1, cy, 9, -M_PI / 3, M_PI / 3);
		cairo_stroke(cr);
	}
}

static void glyph_full(cairo_t *cr, double cx, double cy, bool exit) {
	cairo_set_line_width(cr, 2);
	/* Four corners: arms point in toward the middle to go full screen, out
	 * from a small square to leave it */
	double r = exit ? 3 : 8, arm = exit ? 5 : -5;
	for (int i = 0; i < 4; i++) {
		double sx = i & 1 ? 1 : -1, sy = i & 2 ? 1 : -1;
		cairo_move_to(cr, cx + sx * r, cy + sy * (r + arm));
		cairo_line_to(cr, cx + sx * r, cy + sy * r);
		cairo_line_to(cr, cx + sx * (r + arm), cy + sy * r);
		cairo_stroke(cr);
	}
}

/* A slider's track: filled to frac, with a thumb */
static void draw_track(struct c8ui_widget *w, cairo_t *cr, double x,
		double width, double cy, double frac, double buffered, bool hot,
		bool active) {
	struct transport *t = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double alpha = w->disabled ? 0.4 : 1;
	c8ui_set_source(cr, c.fg, 0.25 * alpha);
	cairo_rectangle(cr, x, cy - TRACK_H / 2.0, width, TRACK_H);
	cairo_fill(cr);
	if (buffered > 0) {
		c8ui_set_source(cr, c.fg, 0.35 * alpha);
		cairo_rectangle(cr, x, cy - TRACK_H / 2.0, width * buffered, TRACK_H);
		cairo_fill(cr);
	}
	c8ui_set_source(cr, active || hot ? c.accent : c.fg, alpha);
	cairo_rectangle(cr, x, cy - TRACK_H / 2.0, width * frac, TRACK_H);
	cairo_fill(cr);
	/* Chapters: a gap in the bar where each starts, but not at 0 */
	for (int i = 0; i < t->mark_count && t->duration > 0; i++) {
		double m = t->marks[i] / t->duration;
		if (m <= 0.002 || m >= 1) {
			continue;
		}
		c8ui_set_source(cr, c.bg, alpha);
		cairo_rectangle(cr, round(x + width * m) - 1, cy - TRACK_H / 2.0 - 1,
			2, TRACK_H + 2);
		cairo_fill(cr);
	}
	c8ui_set_source(cr, c.fg, alpha);
	cairo_rectangle(cr, x + width * frac - THUMB_W / 2.0, cy - THUMB_H / 2.0,
		THUMB_W, THUMB_H);
	cairo_fill(cr);
}

static double seek_frac(struct transport *t) {
	if (t->duration <= 0) {
		return 0;
	}
	double p = t->live && t->drag == ZONE_SEEK ? t->drag_value : t->position;
	return p < 0 ? 0 : p > t->duration ? 1 : p / t->duration;
}

static void transport_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct transport *t = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect z[ZONE_COUNT];
	zones(w, z);
	double alpha = w->disabled ? 0.4 : 1;
	bool kbd = w->focused && w->root && w->root->focus_visible;

	for (int i = ZONE_PREV; i <= ZONE_NEXT; i++) {
		if (z[i].width <= 0) {
			continue;
		}
		bool hot = t->hover == i, down = hot && w->pressed;
		round_button(cr, z[i], c.fg, c.bg, hot, down, alpha);
		c8ui_set_source(cr, down ? c.bg : c.fg, alpha);
		double cx = z[i].x + BUTTON / 2.0, cy = z[i].y + BUTTON / 2.0;
		if (i == ZONE_PLAY) {
			if (t->playing) {
				glyph_pause(cr, cx, cy);
			} else {
				glyph_play(cr, cx, cy);
			}
		} else {
			glyph_skip(cr, cx, cy, i == ZONE_NEXT);
		}
	}

	/* Seek bar, with the times */
	struct c8ui_rect s = z[ZONE_SEEK];
	if (s.width > 0) {
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_CAPTION);
		bool times = w->rect.width >= NARROW_TIME;
		double tx = s.x, tw = s.width;
		char buf[24];
		double ty = w->rect.y + HEIGHT / 2.0;
		if (times) {
			double bw, bh;
			format_time(t->live && t->drag == ZONE_SEEK ? t->drag_value :
				t->position, buf, sizeof(buf));
			c8ui_text_size(c8ui_widget_font(w), font, buf, 0, 0, &bw, &bh);
			c8ui_set_source(cr, c.fg, alpha);
			c8ui_text_draw(cr, c8ui_widget_font(w), font, buf, s.x,
				ty - bh / 2, 0, 0);
			tx += TIME_W;
			tw -= 2 * TIME_W;
			if (t->duration > 0) {
				format_time(t->duration, buf, sizeof(buf));
				c8ui_text_size(c8ui_widget_font(w), font, buf, 0, 0, &bw, &bh);
				c8ui_text_draw(cr, c8ui_widget_font(w), font, buf,
					s.x + s.width - bw, ty - bh / 2, 0, 0);
			}
		}
		if (tw > 0) {
			if (t->duration > 0) {
				draw_track(w, cr, tx, tw, ty, seek_frac(t), t->buffered,
					t->hover == ZONE_SEEK, t->drag == ZONE_SEEK);
			} else {
				/* Nothing to seek in (a stream): a plain line */
				c8ui_set_source(cr, c.fg, 0.25 * alpha);
				cairo_rectangle(cr, tx, ty - TRACK_H / 2.0, tw, TRACK_H);
				cairo_fill(cr);
			}
		}
	}

	if (z[ZONE_MUTE].width > 0) {
		bool hot = t->hover == ZONE_MUTE, down = hot && w->pressed;
		round_button(cr, z[ZONE_MUTE], c.fg, c.bg, hot, down, alpha);
		c8ui_set_source(cr, down ? c.bg : c.fg, alpha);
		glyph_speaker(cr, z[ZONE_MUTE].x + BUTTON / 2.0,
			z[ZONE_MUTE].y + BUTTON / 2.0, t->muted, t->volume);
	}
	if (z[ZONE_VOLUME].width > 0) {
		double v = t->live && t->drag == ZONE_VOLUME ? t->drag_value : t->volume;
		draw_track(w, cr, z[ZONE_VOLUME].x + THUMB_W / 2.0,
			z[ZONE_VOLUME].width - THUMB_W, w->rect.y + HEIGHT / 2.0,
			t->muted ? 0 : v, 0, t->hover == ZONE_VOLUME, t->drag == ZONE_VOLUME);
	}
	if (z[ZONE_FULL].width > 0) {
		bool hot = t->hover == ZONE_FULL, down = hot && w->pressed;
		round_button(cr, z[ZONE_FULL], c.fg, c.bg, hot, down, alpha);
		c8ui_set_source(cr, down ? c.bg : c.fg, alpha);
		glyph_full(cr, z[ZONE_FULL].x + BUTTON / 2.0,
			z[ZONE_FULL].y + BUTTON / 2.0, t->fullscreen);
	}
	if (kbd) {
		c8ui_set_source(cr, c.fg, 1);
		c8ui_dotted_rect(cr, w->rect.x + 0.5, w->rect.y + 0.5,
			w->rect.width - 1, HEIGHT - 1);
	}
}

static void emit(struct c8ui_widget *w, enum c8ui_transport_action action,
		double value) {
	struct transport *t = w->data;
	if (t->fn) {
		t->fn(w, action, value, t->data);
	}
}

static enum zone zone_at(struct c8ui_widget *w, double x, double y) {
	struct c8ui_rect z[ZONE_COUNT];
	zones(w, z);
	for (int i = 0; i < ZONE_COUNT; i++) {
		if (z[i].width > 0 && c8ui_rect_contains(&z[i], x, y)) {
			return i;
		}
	}
	return ZONE_NONE;
}

/* Where a slider's track starts and how long it is */
static void track_span(struct c8ui_widget *w, enum zone zone, double *x,
		double *width) {
	struct c8ui_rect z[ZONE_COUNT];
	zones(w, z);
	if (zone == ZONE_VOLUME) {
		*x = z[zone].x + THUMB_W / 2.0;
		*width = z[zone].width - THUMB_W;
		return;
	}
	bool times = w->rect.width >= NARROW_TIME;
	*x = z[zone].x + (times ? TIME_W : 0);
	*width = z[zone].width - (times ? 2 * TIME_W : 0);
}

static double value_at(struct c8ui_widget *w, enum zone zone, double px) {
	struct transport *t = w->data;
	double x, width;
	track_span(w, zone, &x, &width);
	double f = width > 0 ? (px - x) / width : 0;
	f = f < 0 ? 0 : f > 1 ? 1 : f;
	return zone == ZONE_SEEK ? f * t->duration : f;
}

static void press_zone(struct c8ui_widget *w, enum zone zone) {
	struct transport *t = w->data;
	switch (zone) {
	case ZONE_PLAY:
		emit(w, t->playing ? C8UI_TRANSPORT_PAUSE : C8UI_TRANSPORT_PLAY, 0);
		break;
	case ZONE_PREV:
		emit(w, C8UI_TRANSPORT_PREVIOUS, 0);
		break;
	case ZONE_NEXT:
		emit(w, C8UI_TRANSPORT_NEXT, 0);
		break;
	case ZONE_MUTE:
		emit(w, C8UI_TRANSPORT_MUTE, t->muted ? 0 : 1);
		break;
	case ZONE_FULL:
		emit(w, C8UI_TRANSPORT_FULLSCREEN, t->fullscreen ? 0 : 1);
		break;
	default:
		break;
	}
}

static void drag_to(struct c8ui_widget *w, double x) {
	struct transport *t = w->data;
	t->drag_value = value_at(w, t->drag, x);
	t->live = true;
	c8ui_widget_queue_draw(w);
	emit(w, t->drag == ZONE_SEEK ? C8UI_TRANSPORT_SEEK : C8UI_TRANSPORT_VOLUME,
		t->drag_value);
}

static bool transport_event(struct c8ui_widget *w,
		const struct c8ui_event *ev) {
	struct transport *t = w->data;
	if (w->disabled) {
		return false;
	}
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		if (t->drag != ZONE_NONE) {
			drag_to(w, ev->x);
			return true;
		}
		enum zone z = zone_at(w, ev->x, ev->y);
		if (z != t->hover) {
			t->hover = z;
			c8ui_widget_queue_draw(w);
		}
		return false;
	}
	case C8UI_EVENT_LEAVE:
		t->hover = ZONE_NONE;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS: {
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		enum zone z = zone_at(w, ev->x, ev->y);
		if ((z == ZONE_SEEK && t->duration > 0) || z == ZONE_VOLUME) {
			double x, width;
			track_span(w, z, &x, &width);
			/* Not the time text beside the bar */
			if (ev->x >= x - THUMB_W && ev->x <= x + width + THUMB_W) {
				t->drag = z;
				drag_to(w, ev->x);
				return true;
			}
			return true;
		}
		t->hover = z;
		return z != ZONE_NONE;
	}
	case C8UI_EVENT_RELEASE: {
		if (t->drag != ZONE_NONE) {
			enum zone z = t->drag;
			double value = value_at(w, z, ev->x);
			t->drag = ZONE_NONE;
			t->live = false;
			if (z == ZONE_SEEK) {
				t->position = value;
			} else {
				t->volume = value;
				t->muted = false;
			}
			c8ui_widget_queue_draw(w);
			emit(w, z == ZONE_SEEK ? C8UI_TRANSPORT_SEEK :
				C8UI_TRANSPORT_VOLUME, value);
			return true;
		}
		enum zone z = zone_at(w, ev->x, ev->y);
		if (z != ZONE_NONE && z == t->hover) {
			press_zone(w, z);
		}
		c8ui_widget_queue_draw(w);
		return true;
	}
	case C8UI_EVENT_SCROLL:
		if (zone_at(w, ev->x, ev->y) == ZONE_VOLUME ||
				zone_at(w, ev->x, ev->y) == ZONE_MUTE) {
			double v = t->volume + (ev->dy < 0 ? VOLUME_STEP : -VOLUME_STEP);
			t->volume = v < 0 ? 0 : v > 1 ? 1 : v;
			c8ui_widget_queue_draw(w);
			emit(w, C8UI_TRANSPORT_VOLUME, t->volume);
			return true;
		}
		return false;
	case C8UI_EVENT_KEY: {
		if (ev->mods & ~C8UI_MOD_SHIFT) {
			return false;
		}
		switch (ev->sym) {
		case XKB_KEY_space:
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
			press_zone(w, ZONE_PLAY);
			return true;
		case XKB_KEY_Left:
		case XKB_KEY_Right: {
			if (t->duration <= 0) {
				return false;
			}
			double p = t->position + (ev->sym == XKB_KEY_Right ? SEEK_STEP :
				-SEEK_STEP);
			t->position = p < 0 ? 0 : p > t->duration ? t->duration : p;
			c8ui_widget_queue_draw(w);
			emit(w, C8UI_TRANSPORT_SEEK, t->position);
			return true;
		}
		case XKB_KEY_Up:
		case XKB_KEY_Down: {
			double v = t->volume + (ev->sym == XKB_KEY_Up ? VOLUME_STEP :
				-VOLUME_STEP);
			t->volume = v < 0 ? 0 : v > 1 ? 1 : v;
			c8ui_widget_queue_draw(w);
			emit(w, C8UI_TRANSPORT_VOLUME, t->volume);
			return true;
		}
		case XKB_KEY_m:
			press_zone(w, ZONE_MUTE);
			return true;
		case XKB_KEY_f:
			if (t->show_full) {
				press_zone(w, ZONE_FULL);
				return true;
			}
			return false;
		default:
			return false;
		}
	}
	case C8UI_EVENT_FOCUS_IN:
	case C8UI_EVENT_FOCUS_OUT:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static void transport_destroy(struct c8ui_widget *w) {
	struct transport *t = w->data;
	free(t->marks);
	free(t);
}

static const struct c8ui_widget_impl transport_impl = {
	.name = "transport",
	.measure = transport_measure,
	.draw = transport_draw,
	.event = transport_event,
	.destroy = transport_destroy,
};

struct c8ui_widget *c8ui_transport_new(c8ui_transport_fn fn, void *data) {
	struct transport *t = calloc(1, sizeof(*t));
	t->fn = fn;
	t->data = data;
	t->hover = t->drag = ZONE_NONE;
	t->volume = 1;
	t->show_full = true;
	struct c8ui_widget *w = c8ui_widget_new(&transport_impl, t);
	w->focusable = true;
	w->fill = true;
	return w;
}

void c8ui_transport_set_playing(struct c8ui_widget *w, bool playing) {
	((struct transport *)w->data)->playing = playing;
	c8ui_widget_queue_draw(w);
}

void c8ui_transport_set_position(struct c8ui_widget *w, double seconds) {
	struct transport *t = w->data;
	t->position = seconds < 0 ? 0 : seconds;
	if (!t->live) {
		c8ui_widget_queue_draw(w);
	}
}

void c8ui_transport_set_duration(struct c8ui_widget *w, double seconds) {
	((struct transport *)w->data)->duration = seconds > 0 ? seconds : 0;
	c8ui_widget_queue_draw(w);
}

void c8ui_transport_set_buffered(struct c8ui_widget *w, double fraction) {
	struct transport *t = w->data;
	t->buffered = fraction < 0 ? 0 : fraction > 1 ? 1 : fraction;
	c8ui_widget_queue_draw(w);
}

void c8ui_transport_set_volume(struct c8ui_widget *w, double volume, bool muted) {
	struct transport *t = w->data;
	if (t->live && t->drag == ZONE_VOLUME) {
		return;
	}
	t->volume = volume < 0 ? 0 : volume > 1 ? 1 : volume;
	t->muted = muted;
	c8ui_widget_queue_draw(w);
}

void c8ui_transport_set_fullscreen(struct c8ui_widget *w, bool fullscreen) {
	((struct transport *)w->data)->fullscreen = fullscreen;
	c8ui_widget_queue_draw(w);
}

void c8ui_transport_set_buttons(struct c8ui_widget *w, bool skip,
		bool fullscreen) {
	struct transport *t = w->data;
	t->show_skip = skip;
	t->show_full = fullscreen;
	c8ui_widget_queue_draw(w);
}

bool c8ui_transport_is_live(struct c8ui_widget *w) {
	return ((struct transport *)w->data)->live;
}

void c8ui_transport_set_marks(struct c8ui_widget *w, const double *seconds,
		int count) {
	struct transport *t = w->data;
	free(t->marks);
	t->marks = NULL;
	t->mark_count = 0;
	if (count > 0 && seconds) {
		t->marks = malloc(count * sizeof(double));
		memcpy(t->marks, seconds, count * sizeof(double));
		t->mark_count = count;
	}
	c8ui_widget_queue_draw(w);
}
