/*
 * The player's page. It draws nothing where the video is: the window
 * is see-through there and the video lies under it. Over the video, at
 * the top the back button and the title, at the bottom the transport
 * row, both on a dark band; they show while the pointer moves (or a key
 * is pressed) and go CONTROLS_MS after, the pointer with them.
 *
 * A click plays or pauses, two go full screen, the wheel is the volume,
 * a right click the app bar. An all-round video turns with a drag, and
 * Ctrl and the wheel widen or narrow the view.
 */
#include <math.h>
#include <string.h>
#include "video.h"

#define CONTROLS_MS 3000
#define DOUBLE_MS 400
#define DRAG_START 4
#define TOP_H 88
#define BOTTOM_PAD 12

static struct {
	struct c8ui_widget *stage, *top, *back, *title, *transport, *ring;
	struct stage_hooks hooks;
	bool shown; // the controls
	bool hold; // a flyout or the app bar is up: they stay
	void *timer;
	bool fullscreen, skip;
	/* The press in hand */
	bool pressing, dragged;
	double press_x, press_y, last_x, last_y;
	gint64 clicked_at; // the last click, for a second one
	double pinch; // the scale the pinch in hand last said
	struct c8ui_rect sub_box; // where the subtitle line was last drawn
} s;

static void subtitle_moved(void);

static void set_shown(bool shown) {
	if (s.stage == NULL) {
		return;
	}
	if (shown != s.shown) {
		s.shown = shown;
		c8ui_widget_set_hidden(s.top, !shown);
		c8ui_widget_set_hidden(s.transport, !shown);
		c8ui_widget_queue_layout(s.stage);
		subtitle_moved();
	}
	c8ui_widget_set_cursor(s.stage, shown ? C8UI_CURSOR_DEFAULT :
		C8UI_CURSOR_NONE);
}

static bool may_hide(void) {
	return !s.hold && !(s.hooks.busy && s.hooks.busy()) && vd.active && vd.loaded && !vd.paused && !vd.ended &&
		!s.pressing;
}

static int hide_due(void *data) {
	s.timer = NULL;
	if (may_hide()) {
		set_shown(false);
	}
	return 0;
}

static void disarm(void) {
	if (s.timer && s.stage && s.stage->root) {
		c8ui_root_timer_remove(s.stage->root, s.timer);
	}
	s.timer = NULL;
}

static void arm(void) {
	disarm();
	if (s.stage && s.stage->root) {
		s.timer = c8ui_root_timer_add(s.stage->root, CONTROLS_MS, hide_due,
			NULL);
	}
}

void stage_wake(void) {
	set_shown(true);
	arm();
}

void stage_hold(bool hold) {
	s.hold = hold;
	if (hold) {
		set_shown(true);
	} else {
		arm();
	}
}

void stage_focus(void) {
	if (s.stage) {
		c8ui_widget_grab_focus(s.stage);
	}
}

/* The window's pointer left it: nothing keeps the controls up */
static void pointer_left(struct c8ui_window *win, void *data) {
	if (s.stage) {
		arm();
	}
}

static void transport(struct c8ui_widget *w, enum c8ui_transport_action action,
		double value, void *data) {
	switch (action) {
	case C8UI_TRANSPORT_PLAY:
		player_set_paused(false);
		break;
	case C8UI_TRANSPORT_PAUSE:
		player_set_paused(true);
		break;
	case C8UI_TRANSPORT_PREVIOUS:
		if (s.hooks.previous) {
			s.hooks.previous();
		}
		break;
	case C8UI_TRANSPORT_NEXT:
		if (s.hooks.next) {
			s.hooks.next();
		}
		break;
	case C8UI_TRANSPORT_SEEK:
		player_seek(value);
		break;
	case C8UI_TRANSPORT_VOLUME:
		player_set_volume(value);
		break;
	case C8UI_TRANSPORT_MUTE:
		player_set_muted(value > 0.5);
		break;
	case C8UI_TRANSPORT_FULLSCREEN:
		if (s.hooks.fullscreen) {
			s.hooks.fullscreen(value > 0.5);
		}
		break;
	}
	stage_wake();
}

/* Subtitles we draw (the picture is taken apart: see player.c), white on
 * a dark box, centred above the controls; flat over both eyes, as 3D
 * discs put theirs */

static struct c8ui_font subtitle_font(void) {
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	font.size = CLAMP(s.stage->rect.height / 24, 16, 40);
	return font;
}

#define SUB_PAD 8
#define SUB_LINES 4

/* Each line centred on its own, under the one before; the box round
 * them all (0 wide: nothing to show). draw: and draw them. */
/* Where a piece of a picture subtitle lands */
struct sub_place {
	double cx, cy; // the part of the canvas shown: its top left
	double sx, sy; // canvas pixels to ours
	double ox, oy; // where that top left is
};

/* Which pieces show: the canvas is one eye's picture as made (fitted
 * into ours, as mpv fits it), unless the subtitles were made for 3D,
 * with a copy in each eye's half: then that half alone, stretched as
 * the picture is */
static bool piece_shows(const struct vd_subpicture *pic,
		const struct vd_subrect *rect, struct sub_place *at) {
	struct c8ui_rect area = player_picture();
	double cw = pic->canvas_w, ch = pic->canvas_h;
	if (cw <= 0 || ch <= 0 || area.width <= 0 || area.height <= 0) {
		return false;
	}
	const struct vd_view *v = player_view();
	bool sbs = v->layout == VD_SBS, tb = v->layout == VD_TB;
	int halves = 0; // 1: some in the first half, 2: the second, 4: across
	for (int i = 0; (sbs || tb) && i < pic->count; i++) {
		const struct vd_subrect *q = &pic->rects[i];
		double lo = sbs ? q->x : q->y, len = sbs ? q->w : q->h;
		double mid = (sbs ? cw : ch) / 2;
		halves |= lo + len <= mid ? 1 : lo >= mid ? 2 : 4;
	}
	*at = (struct sub_place){ 0 };
	if (halves == 3) {
		/* The eye shown is the left one: second when they're swapped */
		int eye = v->swap ? 1 : 0;
		double lo = sbs ? rect->x : rect->y;
		double mid = (sbs ? cw : ch) / 2;
		if ((lo >= mid) != eye) {
			return false;
		}
		if (sbs) {
			cw /= 2;
			at->cx = eye * cw;
		} else {
			ch /= 2;
			at->cy = eye * ch;
		}
		at->sx = area.width / cw;
		at->sy = area.height / ch;
	} else {
		at->sx = at->sy = fmin(area.width / cw, area.height / ch);
	}
	at->ox = area.x + (area.width - cw * at->sx) / 2;
	at->oy = area.y + (area.height - ch * at->sy) / 2;
	return true;
}

static struct c8ui_rect subtitle_picture(cairo_t *cr) {
	const struct vd_subpicture *pic = vd.subpicture;
	double x0 = INFINITY, y0 = INFINITY, x1 = -INFINITY, y1 = -INFINITY;
	for (int i = 0; i < pic->count; i++) {
		const struct vd_subrect *rect = &pic->rects[i];
		struct sub_place at;
		if (!piece_shows(pic, rect, &at)) {
			continue;
		}
		double x = at.ox + (rect->x - at.cx) * at.sx;
		double y = at.oy + (rect->y - at.cy) * at.sy;
		double w = rect->w * at.sx, h = rect->h * at.sy;
		if (cr) {
			cairo_save(cr);
			cairo_rectangle(cr, x, y, w, h);
			cairo_clip(cr);
			cairo_translate(cr, x, y);
			cairo_scale(cr, at.sx, at.sy);
			cairo_set_source_surface(cr, rect->pic, 0, 0);
			cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);
			cairo_paint(cr);
			cairo_restore(cr);
		}
		x0 = fmin(x0, x);
		y0 = fmin(y0, y);
		x1 = fmax(x1, x + w);
		y1 = fmax(y1, y + h);
	}
	if (x1 <= x0) {
		return (struct c8ui_rect){ 0 };
	}
	/* A pixel more round it: the filter reaches past the edges */
	return (struct c8ui_rect){ floor(x0) - 1, floor(y0) - 1,
		ceil(x1) - floor(x0) + 2, ceil(y1) - floor(y0) + 2 };
}

static struct c8ui_rect subtitle_lines(cairo_t *cr) {
	struct c8ui_rect r = s.stage->rect;
	if (vd.own_subtitles && vd.subpicture && r.width > 0) {
		return subtitle_picture(cr);
	}
	if (!vd.own_subtitles || vd.subtitle == NULL || r.width <= 0) {
		return (struct c8ui_rect){ 0 };
	}
	const char *family = c8ui_widget_font(s.stage);
	struct c8ui_font font = subtitle_font();
	double max = r.width * 0.9 - SUB_PAD * 2;
	char **lines = g_strsplit(vd.subtitle, "\n", SUB_LINES);
	double lw[SUB_LINES], lh[SUB_LINES], wide = 0, high = 0;
	int n = 0;
	for (; lines[n] && n < SUB_LINES; n++) {
		c8ui_text_size(family, font, lines[n], max, 2, &lw[n], &lh[n]);
		wide = fmax(wide, lw[n]);
		high += lh[n];
	}
	double bottom = r.y + r.height - (s.shown ?
		s.transport->rect.height + BOTTOM_PAD * 3 : r.height * 0.06);
	struct c8ui_rect b = { floor(r.x + (r.width - wide) / 2 - SUB_PAD),
		floor(bottom - high - SUB_PAD * 2), ceil(wide + SUB_PAD * 2),
		ceil(high + SUB_PAD * 2) };
	if (cr && wide > 0) {
		cairo_set_source_rgba(cr, 0, 0, 0, 0.6);
		cairo_rectangle(cr, b.x, b.y, b.width, b.height);
		cairo_fill(cr);
		c8ui_set_source(cr, 0xffffff, 1);
		double y = b.y + SUB_PAD;
		for (int i = 0; i < n; i++) {
			c8ui_text_draw(cr, family, font, lines[i],
				r.x + (r.width - lw[i]) / 2, y, max, 2);
			y += lh[i];
		}
	}
	g_strfreev(lines);
	return wide > 0 ? b : (struct c8ui_rect){ 0 };
}

static void damage(struct c8ui_rect b) {
	if (b.width > 0) {
		c8ui_widget_queue_draw_rect(s.stage, b.x, b.y, b.width, b.height);
	}
}

/* The line changed, or moved with the controls */
static void subtitle_moved(void) {
	damage(s.sub_box);
	s.sub_box = subtitle_lines(NULL);
	damage(s.sub_box);
}

static void draw_subtitle(cairo_t *cr) {
	s.sub_box = subtitle_lines(cr);
}

void stage_update(unsigned changes) {
	if (s.stage == NULL) {
		return;
	}
	if (changes & VD_CH_SUBTITLES) {
		subtitle_moved();
	}
	if (changes & VD_CH_CHAPTERS) {
		double marks[vd.chapters->len + 1];
		for (guint i = 0; i < vd.chapters->len; i++) {
			marks[i] = g_array_index(vd.chapters, struct vd_chapter, i).time;
		}
		c8ui_transport_set_marks(s.transport, marks, vd.chapters->len);
	}
	if (changes & (VD_CH_STATE | VD_CH_LOADED)) {
		c8ui_transport_set_playing(s.transport,
			vd.active && !vd.paused && !vd.ended);
		bool busy = vd.active && (!vd.loaded || vd.buffering);
		if (busy == s.ring->hidden) {
			s.ring->hidden = !busy;
			c8ui_ring_set_active(s.ring, busy);
		}
		c8ui_widget_queue_draw(s.stage);
		if (may_hide()) {
			if (s.timer == NULL) {
				arm();
			}
		} else {
			set_shown(true);
		}
	}
	if (changes & VD_CH_TIME) {
		c8ui_transport_set_duration(s.transport,
			vd.seekable ? vd.duration : 0);
		if (s.shown) {
			c8ui_transport_set_position(s.transport, vd.position);
		}
	}
	if (changes & VD_CH_VOLUME) {
		c8ui_transport_set_volume(s.transport, vd.volume, vd.muted);
	}
	if (changes & VD_CH_TITLE) {
		c8ui_label_set_text(s.title, vd.title ? vd.title : "");
	}
}

void stage_set_fullscreen(bool fullscreen) {
	s.fullscreen = fullscreen;
	if (s.transport) {
		c8ui_transport_set_fullscreen(s.transport, fullscreen);
	}
}

void stage_set_skip(bool skip) {
	s.skip = skip;
	if (s.transport) {
		c8ui_transport_set_buttons(s.transport, skip, true);
	}
}

static void back_pressed(struct c8ui_widget *w, void *data) {
	if (s.hooks.back) {
		s.hooks.back();
	}
}

/* The widget */

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

static void stage_layout(struct c8ui_widget *w) {
	struct c8ui_rect r = w->rect;
	bool narrow = r.width < C8UI_NARROW_WIDTH;
	double side = narrow ? 12 : 40;
	double tw, th;
	c8ui_widget_measure(s.top, r.width - side * 2, &tw, &th);
	c8ui_widget_layout(s.top, (struct c8ui_rect){ r.x + side,
		r.y + (narrow ? 16 : 28), r.width - side * 2, th });
	c8ui_widget_measure(s.transport, r.width - side * 2, &tw, &th);
	c8ui_widget_layout(s.transport, (struct c8ui_rect){ r.x + side,
		r.y + r.height - th - BOTTOM_PAD, r.width - side * 2, th });
	c8ui_widget_measure(s.ring, r.width, &tw, &th);
	c8ui_widget_layout(s.ring, (struct c8ui_rect){ r.x + (r.width - tw) / 2,
		r.y + (r.height - th) / 2, tw, th });
}

/* Dark towards the edge, clear towards the video */
static void band(cairo_t *cr, double x, double y, double w, double h,
		bool top) {
	cairo_pattern_t *fade = cairo_pattern_create_linear(0, y, 0, y + h);
	cairo_pattern_add_color_stop_rgba(fade, top ? 0 : 1, 0, 0, 0, 0.75);
	cairo_pattern_add_color_stop_rgba(fade, top ? 1 : 0, 0, 0, 0, 0);
	cairo_set_source(cr, fade);
	cairo_rectangle(cr, x, y, w, h);
	cairo_fill(cr);
	cairo_pattern_destroy(fade);
}

static void stage_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_rect r = w->rect;
	if (s.shown) {
		band(cr, r.x, r.y, r.width, TOP_H + 40, true);
		double bh = s.transport->rect.height + BOTTOM_PAD + 60;
		band(cr, r.x, r.y + r.height - bh, r.width, bh, false);
	}
	if (vd.error && !vd.active) {
		const char *family = c8ui_widget_font(w);
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_SUBHEADER);
		char *text = g_strdup_printf("This video can't be played. %s",
			vd.error);
		double max = fmin(r.width - 40, 640), tw, th;
		c8ui_text_size(family, font, text, max, 4, &tw, &th);
		c8ui_set_source(cr, 0xffffff, 1);
		c8ui_text_draw(cr, family, font, text, r.x + (r.width - tw) / 2,
			r.y + (r.height - th) / 2, max, 4);
		g_free(text);
	}
	draw_subtitle(cr);
}

static void turn(double dx, double dy) {
	struct vd_view v = *player_view();
	/* The picture follows the hand, as a map does */
	double per_px = v.fov / fmax(1, s.stage->rect.height);
	v.yaw -= dx * per_px;
	v.pitch += dy * per_px;
	player_set_view(&v);
}

static void clicked(void) {
	gint64 now = g_get_monotonic_time() / 1000;
	bool second = now - s.clicked_at < DOUBLE_MS;
	s.clicked_at = second ? 0 : now;
	if (!vd.active) {
		return;
	}
	/* The second click of two undoes the first's pause */
	player_set_paused(!(vd.paused || vd.ended));
	if (second && s.hooks.fullscreen) {
		s.hooks.fullscreen(!s.fullscreen);
	}
}

static bool stage_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	bool round = player_view()->shape != VD_FLAT;
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
		if (s.pressing) {
			if (!s.dragged && hypot(ev->x - s.press_x, ev->y - s.press_y) >
					DRAG_START) {
				s.dragged = true;
			}
			if (s.dragged && round) {
				turn(ev->x - s.last_x, ev->y - s.last_y);
			}
			s.last_x = ev->x;
			s.last_y = ev->y;
		}
		stage_wake();
		return true;
	case C8UI_EVENT_LEAVE:
		/* Onto the controls (they stay while it's there) or out of the
		 * window (pointer_left starts the wait again) */
		disarm();
		return true;
	case C8UI_EVENT_PRESS:
		c8ui_widget_grab_focus(w);
		if (ev->button == C8UI_BUTTON_LEFT) {
			s.pressing = true;
			s.dragged = false;
			s.press_x = s.last_x = ev->x;
			s.press_y = s.last_y = ev->y;
		}
		stage_wake();
		return true;
	case C8UI_EVENT_RELEASE:
		if (ev->button == C8UI_BUTTON_LEFT && s.pressing) {
			s.pressing = false;
			if (!s.dragged) {
				clicked();
			}
		} else if (ev->button == C8UI_BUTTON_RIGHT) {
			if (s.hooks.context) {
				s.hooks.context();
			}
		} else if (ev->button == C8UI_BUTTON_BACK) {
			back_pressed(NULL, NULL);
		}
		stage_wake();
		return true;
	case C8UI_EVENT_SCROLL: {
		double notches = ev->precise ? ev->dy / 120 : ev->dy / 40;
		if ((ev->mods & C8UI_MOD_CTRL) && round) {
			struct vd_view v = *player_view();
			v.fov *= pow(1.1, notches);
			player_set_view(&v);
		} else if (!(ev->mods & C8UI_MOD_CTRL)) {
			player_set_volume(vd.volume - notches * 0.05);
			stage_wake();
		}
		return true;
	}
	case C8UI_EVENT_PINCH_BEGIN:
		s.pinch = 1;
		return round;
	case C8UI_EVENT_PINCH_UPDATE:
		if (round && ev->scale > 0) {
			/* scale is against the pinch's start: take each step */
			struct vd_view v = *player_view();
			v.fov *= s.pinch / ev->scale;
			s.pinch = ev->scale;
			player_set_view(&v);
		}
		return true;
	case C8UI_EVENT_PINCH_END:
		return true;
	default:
		return false;
	}
}

static void stage_destroy(struct c8ui_widget *w) {
	if (s.stage == w) {
		disarm();
		memset(&s, 0, sizeof(s));
	}
}

static const struct c8ui_widget_impl stage_impl = {
	.name = "stage",
	.measure = stage_measure,
	.layout = stage_layout,
	.draw = stage_draw,
	.event = stage_event,
	.destroy = stage_destroy,
};

struct c8ui_widget *stage_new(const struct stage_hooks *hooks) {
	memset(&s, 0, sizeof(s));
	s.hooks = *hooks;
	s.stage = c8ui_widget_new(&stage_impl, NULL);
	s.stage->fill = true;
	s.stage->expand = true;
	s.stage->focusable = true;
	c8ui_widget_set_scheme(s.stage, C8UI_SCHEME_DARK);

	s.top = c8ui_box_new(C8UI_HORIZONTAL, 20);
	s.back = c8ui_back_button_new(back_pressed, NULL);
	s.back->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(s.top, s.back);
	s.title = c8ui_label_new("", C8UI_TEXT_SUBHEADER);
	c8ui_label_set_max_lines(s.title, 1);
	s.title->expand = true;
	s.title->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(s.top, s.title);
	c8ui_widget_add(s.stage, s.top);

	s.transport = c8ui_transport_new(transport, NULL);
	c8ui_transport_set_buttons(s.transport, false, true);
	c8ui_transport_set_volume(s.transport, vd.volume, vd.muted);
	c8ui_widget_add(s.stage, s.transport);

	s.ring = c8ui_ring_new(0);
	s.ring->hidden = true;
	c8ui_widget_add(s.stage, s.ring);
	s.shown = true;
	return s.stage;
}

/* Once the stage is in a window */
void stage_attach(struct c8ui_window *win) {
	c8ui_window_on_pointer_leave(win, pointer_left, NULL);
}
