/*
 * The folder grid Video opens on: Videos (or the folder of the last
 * video played), its folders as dark tiles and its videos as thumbnails
 * from the shared cache, made in a sandbox when missing, the name under
 * each. A folder opens in place, a video in the player with the
 * folder's others after it. The folder is watched.
 */
#include <math.h>
#include <string.h>
#include <c8ui/c8ui-files.h>
#include "video.h"

#define CELL_W 260
#define CELL_H 190 // a 16:9 picture and the name under it
#define NAME_H 44
#define GRID_GAP 10 // c8ui's list puts this between cells
#define RELOAD_MS 300

static struct {
	struct c8ui_widget *box, *header, *back, *title, *scroll, *list, *note;
	struct c8ui_widget *ring;
	struct browse_hooks hooks;
	char *folder, *top, *select;
	GPtrArray *entries;
	GCancellable *cancel;
	GFileMonitor *monitor;
	guint reload_timer;
	bool narrow;
} b;

static int index_of(struct vd_entry *e) {
	for (guint i = 0; b.entries && i < b.entries->len; i++) {
		if (b.entries->pdata[i] == e) {
			return i;
		}
	}
	return -1;
}

static void got_thumb(cairo_surface_t *thumb, void *data) {
	struct vd_entry *e = data;
	e->thumb_load = NULL;
	e->thumb = thumb;
	e->thumb_failed = thumb == NULL;
	int i = index_of(e);
	if (i >= 0 && b.list) {
		c8ui_list_redraw_item(b.list, i);
	}
}

static void draw_name(cairo_t *cr, struct c8ui_widget *list,
		const struct c8ui_list_item *item, const char *name) {
	const char *family = c8ui_widget_font(list);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	c8ui_set_source(cr, 0xffffff, 1);
	c8ui_text_draw(cr, family, font, name, item->rect.x + 10,
		item->rect.y + item->rect.height - 30, item->rect.width - 20, 1);
}

static void draw_item(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct vd_entry *e = b.entries->pdata[item->index];
	struct c8ui_rect r = item->rect;
	if (e->folder) {
		c8ui_set_source(cr, 0x2b2b2b, 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		/* A folder, drawn in the app bar glyphs' thin white line */
		double fw = round(r.width * 0.34), fh = round(fw * 0.74);
		double fx = round(r.x + (r.width - fw) / 2);
		double fy = round(r.y + (r.height - fh) / 2 - 14);
		c8ui_set_source(cr, 0xffffff, 0.9);
		cairo_set_line_width(cr, 2);
		cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
		cairo_move_to(cr, fx, fy + fh);
		cairo_line_to(cr, fx, fy);
		cairo_line_to(cr, fx + fw * 0.38, fy);
		cairo_line_to(cr, fx + fw * 0.48, fy + fh * 0.16);
		cairo_line_to(cr, fx + fw, fy + fh * 0.16);
		cairo_line_to(cr, fx + fw, fy + fh);
		cairo_close_path(cr);
		cairo_stroke(cr);
		draw_name(cr, list, item, e->name);
	} else {
		/* The picture, a play mark until it comes, and the name under */
		double ph = r.height - NAME_H;
		c8ui_set_source(cr, 0x222222, 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		if (e->thumb) {
			cairo_save(cr);
			cairo_rectangle(cr, r.x, r.y, r.width, ph);
			cairo_clip(cr);
			c8ui_draw_surface_cover(cr, e->thumb, r.x, r.y, r.width, ph);
			cairo_restore(cr);
		} else {
			double s = 22, cx = r.x + r.width / 2, cy = r.y + ph / 2;
			c8ui_set_source(cr, 0xffffff, 0.35);
			cairo_move_to(cr, cx - s * 0.7, cy - s);
			cairo_line_to(cr, cx + s, cy);
			cairo_line_to(cr, cx - s * 0.7, cy + s);
			cairo_close_path(cr);
			cairo_fill(cr);
			if (!e->thumb_failed) {
				if (e->thumb_load == NULL) {
					e->thumb_load = c8ui_thumbnail_load(e->uri,
						C8UI_THUMBNAIL_LARGE, got_thumb, e);
				}
				c8ui_list_not_final(list);
			}
		}
		draw_name(cr, list, item, e->name);
	}
	/* The states, over the picture: white when hovered, the accent when
	 * picked, as Metro's grids */
	struct c8ui_colors c = c8ui_widget_colors(list);
	if (item->selected || item->cursor || item->hovered) {
		uint32_t rgb = item->selected ? c.accent : 0xffffff;
		c8ui_set_source(cr, rgb, item->selected ? 1 : 0.6);
		cairo_set_line_width(cr, 4);
		cairo_rectangle(cr, r.x + 2, r.y + 2, r.width - 4, r.height - 4);
		cairo_stroke(cr);
	}
	if (item->pressed) {
		c8ui_set_source(cr, 0x000000, 0.25);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
	}
}

static void opened(struct c8ui_widget *list, int index, void *data) {
	if (b.entries == NULL || index < 0 || index >= (int)b.entries->len) {
		return;
	}
	struct vd_entry *e = b.entries->pdata[index];
	if (e->folder) {
		char *uri = g_strdup(e->uri);
		browse_set_folder(uri, NULL);
		g_free(uri);
		return;
	}
	GPtrArray *pics = vd_videos_of(b.entries);
	int at = 0;
	for (guint i = 0; i < pics->len; i++) {
		if (pics->pdata[i] == e) {
			at = i;
		}
	}
	if (b.hooks.open_video) {
		b.hooks.open_video(pics, at);
	}
	g_ptr_array_unref(pics);
}

static void context(struct c8ui_widget *list, int index, double x, double y,
		void *data) {
	if (index >= 0) {
		c8ui_list_select(list, index);
	}
	if (b.hooks.context) {
		b.hooks.context();
	}
}

static void select_uri(const char *uri) {
	for (guint i = 0; uri && b.entries && i < b.entries->len; i++) {
		struct vd_entry *e = b.entries->pdata[i];
		if (strcmp(e->uri, uri) == 0) {
			c8ui_list_select(b.list, i);
			c8ui_list_reveal(b.list, i);
			return;
		}
	}
}

static void listed(GPtrArray *entries, const char *error, void *data) {
	g_clear_object(&b.cancel);
	if (b.list == NULL) {
		return;
	}
	c8ui_ring_set_active(b.ring, false);
	b.ring->hidden = true;
	char *keep = NULL;
	int sel = c8ui_list_get_selected(b.list);
	if (b.select == NULL && sel >= 0 && b.entries &&
			sel < (int)b.entries->len) {
		keep = g_strdup(((struct vd_entry *)b.entries->pdata[sel])->uri);
	}
	if (b.entries) {
		g_ptr_array_unref(b.entries);
	}
	b.entries = entries ? g_ptr_array_ref(entries) : NULL;
	c8ui_list_set_count(b.list, b.entries ? b.entries->len : 0);
	c8ui_list_redraw(b.list);
	select_uri(b.select ? b.select : keep);
	g_clear_pointer(&b.select, g_free);
	g_free(keep);
	if (error) {
		char *msg = g_strdup_printf("This folder can't be opened. %s", error);
		c8ui_label_set_text(b.note, msg);
		g_free(msg);
	} else {
		c8ui_label_set_text(b.note, "There are no videos here.");
	}
	c8ui_widget_set_hidden(b.note, b.entries && b.entries->len > 0);
	c8ui_widget_queue_layout(b.box);
}

static void load(void) {
	if (b.cancel) {
		g_cancellable_cancel(b.cancel);
		g_object_unref(b.cancel);
	}
	b.cancel = g_cancellable_new();
	vd_list_folder(b.folder, true, b.cancel, listed, NULL);
}

static gboolean reload_due(gpointer data) {
	b.reload_timer = 0;
	load();
	return G_SOURCE_REMOVE;
}

static void folder_changed(GFileMonitor *m, GFile *file, GFile *other,
		GFileMonitorEvent event, gpointer data) {
	if (event == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT ||
			event == G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED) {
		return;
	}
	if (b.reload_timer) {
		g_source_remove(b.reload_timer);
	}
	b.reload_timer = g_timeout_add(RELOAD_MS, reload_due, NULL);
}

static void update_header(void) {
	bool top = b.top && b.folder && strcmp(b.top, b.folder) == 0;
	char *parent = b.folder ? vd_parent_uri(b.folder) : NULL;
	c8ui_widget_set_hidden(b.back, top || parent == NULL);
	g_free(parent);
	GFile *f = g_file_new_for_uri(b.folder);
	char *name = NULL;
	GFileInfo *info = g_file_query_info(f,
		G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NONE,
		NULL, NULL);
	if (info) {
		name = g_strdup(g_file_info_get_display_name(info));
		g_object_unref(info);
	}
	g_object_unref(f);
	c8ui_label_set_text(b.title, name ? name : "Videos");
	g_free(name);
}

void browse_set_folder(const char *uri, const char *select) {
	if (uri == NULL) {
		return;
	}
	bool same = b.folder && strcmp(b.folder, uri) == 0;
	g_free(b.select);
	b.select = g_strdup(select);
	if (same && b.entries) {
		/* Already shown: only pick the picture */
		select_uri(b.select);
		g_clear_pointer(&b.select, g_free);
		return;
	}
	g_free(b.folder);
	b.folder = g_strdup(uri);
	if (b.entries) {
		g_ptr_array_unref(b.entries);
		b.entries = NULL;
	}
	if (b.list) {
		c8ui_list_set_count(b.list, 0);
		c8ui_list_select(b.list, -1);
		c8ui_scroll_to(b.scroll, 0);
		c8ui_widget_set_hidden(b.note, true);
		b.ring->hidden = false;
		c8ui_ring_set_active(b.ring, true);
		update_header();
	}
	if (b.monitor) {
		g_signal_handlers_disconnect_by_func(b.monitor, folder_changed, NULL);
		g_file_monitor_cancel(b.monitor);
		g_clear_object(&b.monitor);
	}
	GFile *f = g_file_new_for_uri(uri);
	b.monitor = g_file_monitor_directory(f, G_FILE_MONITOR_WATCH_MOVES, NULL,
		NULL);
	g_object_unref(f);
	if (b.monitor) {
		g_signal_connect(b.monitor, "changed", G_CALLBACK(folder_changed),
			NULL);
	}
	load();
	if (b.hooks.changed) {
		b.hooks.changed();
	}
}

void browse_select(const char *uri) {
	char *parent = vd_parent_uri(uri);
	if (parent) {
		browse_set_folder(parent, uri);
	}
	g_free(parent);
}

const char *browse_folder(void) {
	return b.folder;
}

GPtrArray *browse_entries(void) {
	return b.entries;
}

GPtrArray *browse_videos(void) {
	return vd_videos_of(b.entries);
}

bool browse_up(void) {
	if (b.folder == NULL || (b.top && strcmp(b.top, b.folder) == 0)) {
		return false;
	}
	char *parent = vd_parent_uri(b.folder);
	if (parent == NULL) {
		return false;
	}
	char *from = g_strdup(b.folder);
	browse_set_folder(parent, from);
	g_free(from);
	g_free(parent);
	return true;
}

void browse_refresh(void) {
	load();
}

static void back_pressed(struct c8ui_widget *w, void *data) {
	browse_up();
}

void browse_set_narrow(bool narrow) {
	b.narrow = narrow;
	if (b.box == NULL) {
		return;
	}
	double cw = CELL_W, ch = CELL_H;
	if (narrow) {
		/* Two across, filling the width */
		double width = c8ui_root_width(b.box->root) - 40;
		cw = fmax(100, floor((width - GRID_GAP) / 2));
		ch = round(cw * 9 / 16) + NAME_H;
	}
	c8ui_list_set_mode(b.list, C8UI_LIST_GRID, cw, ch);
}

static void box_gone(struct c8ui_widget *w, void *data) {
	if (b.box != w) {
		return;
	}
	if (b.cancel) {
		g_cancellable_cancel(b.cancel);
		g_clear_object(&b.cancel);
	}
	if (b.reload_timer) {
		g_source_remove(b.reload_timer);
		b.reload_timer = 0;
	}
	b.box = b.header = b.back = b.title = b.scroll = b.list = b.note = NULL;
	b.ring = NULL;
}

struct c8ui_widget *browse_new(const struct browse_hooks *hooks) {
	b.hooks = *hooks;
	if (b.top == NULL) {
		b.top = vd_videos_uri();
	}
	b.box = c8ui_box_new(C8UI_VERTICAL, 24);
	b.box->fill = true;
	b.box->expand = true;
	b.box->on_destroy = box_gone;
	c8ui_box_set_padding(b.box, 120, 44, 40, 0);
	c8ui_box_set_narrow_padding(b.box, 20, 24, 20, 0);
	b.header = c8ui_box_new(C8UI_HORIZONTAL, 20);
	b.back = c8ui_back_button_new(back_pressed, NULL);
	b.back->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(b.header, b.back);
	b.title = c8ui_label_new("Videos", C8UI_TEXT_HEADER);
	c8ui_label_set_max_lines(b.title, 1);
	b.title->expand = true;
	c8ui_widget_add(b.header, b.title);
	b.ring = c8ui_ring_new(0);
	b.ring->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(b.header, b.ring);
	c8ui_widget_add(b.box, b.header);
	b.note = c8ui_label_new("", C8UI_TEXT_BODY);
	c8ui_label_set_color(b.note, C8UI_COLOR_SECONDARY);
	b.note->hidden = true;
	c8ui_widget_add(b.box, b.note);
	b.list = c8ui_list_new(C8UI_LIST_GRID, CELL_W, CELL_H, draw_item, NULL);
	c8ui_list_set_keep(b.list, true);
	c8ui_list_set_click_opens(b.list, true);
	c8ui_list_on_open(b.list, opened, NULL);
	c8ui_list_on_context(b.list, context, NULL);
	b.list->fill = true;
	/* Room under the last row, as Metro pages end */
	struct c8ui_widget *inner = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(inner, 0, 0, 0, 40);
	inner->fill = true;
	c8ui_widget_add(inner, b.list);
	b.scroll = c8ui_scroll_new(inner);
	b.scroll->fill = true;
	b.scroll->expand = true;
	c8ui_widget_add(b.box, b.scroll);
	browse_set_narrow(b.narrow);
	if (b.folder) {
		/* A new window (the old one closed): show the folder again */
		char *uri = b.folder;
		b.folder = NULL;
		browse_set_folder(uri, NULL);
		g_free(uri);
	}
	return b.box;
}

struct c8ui_widget *browse_list(void) {
	return b.list;
}
