/*
 * A list of posts and where it comes from: the timeline, a feed, a list,
 * someone's posts, a search, a thread, the notifications, people. It
 * loads a page at a time, the next when its end is drawn. The entries
 * are cards of their own heights in a c8ui list of spans: a cell is a
 * column wide and UNIT high, and a card takes as many rows as it needs.
 */
#include <math.h>
#include <string.h>
#include "app.h"

/* A row of the list: small, so a card is no taller than it needs; the list
 * puts 10 between rows too */
#define UNIT 2
#define ROW_GAP 10
#define PAGE "30"
#define POSTS_AT_ONCE 25 // getPosts takes that many

static GPtrArray *views; // every one alive
static struct sky_item more_item = { .kind = SKY_ITEM_MORE };

struct request {
	struct feedview *fv;
	int serial;
	bool more;
};

static void load(struct feedview *fv, bool more);

struct feedview *view_new(enum view_kind kind, const char *param,
		const char *filter, const char *name) {
	struct feedview *fv = g_new0(struct feedview, 1);
	fv->refs = 1;
	fv->kind = kind;
	fv->param = g_strdup(param);
	fv->filter = g_strdup(filter);
	fv->name = g_strdup(name);
	fv->items = g_ptr_array_new_with_free_func(sky_item_free);
	if (views == NULL) {
		views = g_ptr_array_new();
	}
	g_ptr_array_add(views, fv);
	return fv;
}

struct feedview *view_ref(struct feedview *fv) {
	fv->refs++;
	return fv;
}

void view_unref(struct feedview *fv) {
	if (fv == NULL || --fv->refs > 0) {
		return;
	}
	g_ptr_array_remove(views, fv);
	g_ptr_array_unref(fv->items);
	g_free(fv->param);
	g_free(fv->filter);
	g_free(fv->name);
	g_free(fv->cursor);
	g_free(fv->error);
	g_free(fv);
}

static bool has_more(struct feedview *fv) {
	return fv->items->len > 0 && !fv->ended;
}

static int count(struct feedview *fv) {
	return (int)fv->items->len + has_more(fv);
}

static struct sky_item *item_at(struct feedview *fv, int i) {
	if (i < 0 || i >= count(fv)) {
		return NULL;
	}
	return i < (int)fv->items->len ? fv->items->pdata[i] : &more_item;
}

struct sky_item *view_selected(struct feedview *fv) {
	if (fv->list == NULL) {
		return NULL;
	}
	struct sky_item *it = item_at(fv, c8ui_list_get_selected(fv->list));
	return it == &more_item ? NULL : it;
}

void view_changed(struct feedview *fv) {
	if (fv->list == NULL) {
		return;
	}
	c8ui_list_set_count(fv->list, count(fv));
	c8ui_list_redraw(fv->list);
	const char *say = NULL;
	if (fv->items->len == 0) {
		say = fv->error ? fv->error : fv->loading || !fv->loaded ? "Loading…" :
			fv->kind == VIEW_NOTICES ? "Nothing has happened yet." :
			fv->kind == VIEW_SEARCH || fv->kind == VIEW_PEOPLE ?
			"Nothing found." : "Nothing here yet.";
	}
	if (say) {
		c8ui_label_set_text(fv->status, say);
	}
	c8ui_widget_set_hidden(fv->status, say == NULL);
}

/* The list's side */

static void spans(struct c8ui_widget *list, int index, int *cols, int *rows,
		void *data) {
	struct feedview *fv = data;
	struct sky_item *it = item_at(fv, index);
	*cols = 1;
	*rows = 1;
	if (it) {
		/* The post a thread is about is two columns wide, where there are */
		double width = fv->width;
		if (it->focus && fv->columns > 1) {
			*cols = 2;
			width = 2 * width + COLUMN_GAP;
		}
		double h = card_height(c8ui_widget_font(list), it, width);
		*rows = (int)ceil((h + ROW_GAP) / (UNIT + ROW_GAP));
	}
}

static gboolean more_idle(gpointer data) {
	struct feedview *fv = data;
	if (fv->list && !fv->loading && has_more(fv)) {
		load(fv, true);
	}
	view_unref(fv);
	return G_SOURCE_REMOVE;
}

static void draw_tile(struct c8ui_widget *list, cairo_t *cr,
	const struct c8ui_list_item *item, void *data);

static void draw_item(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct feedview *fv = data;
	if (fv->tiles) {
		draw_tile(list, cr, item, data);
		return;
	}
	struct sky_item *it = item_at(fv, item->index);
	if (it == NULL) {
		return;
	}
	if (!card_draw(cr, c8ui_widget_font(list), it, item->rect, item)) {
		c8ui_list_not_final(list);
	}
	if (it == &more_item && !fv->loading) {
		/* Its end is in sight: the next page */
		g_idle_add(more_idle, view_ref(fv));
	}
}

/* Tiles: a post's first picture (or its video's), cover-filled, a
 * count in the corner when it has more; its words on blue when its
 * pictures aren't shown */
#define TILES_ACROSS 3

static double tile_side(struct feedview *fv) {
	return floor((fv->width - (TILES_ACROSS - 1) * COLUMN_GAP) /
		TILES_ACROSS);
}

static void draw_tile(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct feedview *fv = data;
	struct sky_item *it = item_at(fv, item->index);
	if (it == NULL) {
		return;
	}
	struct c8ui_rect r = item->rect;
	const char *family = c8ui_widget_font(list);
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	struct sky_post *p = it == &more_item ? NULL : it->post;
	bool shown = p && sky_settings.images &&
		(!p->sensitive || sky_settings.sensitive);
	const char *url = !shown ? NULL : p->n_images > 0 ? p->images[0].thumb :
		p->video_thumb;
	cairo_surface_t *img = url ? sky_image(url) : NULL;
	if (img) {
		c8ui_draw_surface_cover(cr, img, r.x, r.y, r.width, r.height);
	} else {
		c8ui_set_source(cr, p ? BAR_TILE : CARD, 1);
		cairo_paint(cr);
		if (url) {
			c8ui_list_not_final(list); // on its way
		}
	}
	if (p && !img && !url) {
		/* Pictures off, or hidden: the words instead */
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION),
			p->sensitive ? "Sensitive picture" : p->text ? p->text : "",
			r.x + 8, r.y + 8, r.width - 16, 5);
	} else if (p == NULL) {
		c8ui_set_source(cr, INK, 0.6);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION),
			"Loading more…", r.x + 8, r.y + r.height / 2 - 8, r.width - 16, 1);
	}
	if (p && (p->n_images > 1 || p->video)) {
		/* More pictures, or a video: said in the corner */
		char n[16];
		g_snprintf(n, sizeof(n), p->video ? "▶" : "%d", p->n_images);
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_CAPTION);
		double tw, th;
		c8ui_text_size(family, font, n, 0, 1, &tw, &th);
		double bw = fmax(tw + 10, 22);
		c8ui_set_source(cr, 0x000000, 0.55);
		cairo_rectangle(cr, r.x + r.width - bw - 6, r.y + 6, bw, 20);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, font, n, r.x + r.width - 6 - (bw + tw) / 2,
			r.y + 16 - th / 2, 0, 1);
	}
	if (item->hovered || item->selected || item->pressed) {
		c8ui_set_source(cr, item->pressed ? 0x000000 : 0xffffff,
			item->pressed ? 0.2 : item->selected ? 0.25 : 0.12);
		cairo_paint(cr);
	}
	cairo_restore(cr);
	if (it == &more_item && !fv->loading) {
		g_idle_add(more_idle, view_ref(fv));
	}
}

/* The list as cards or as tiles, for its width */
static void list_shape(struct feedview *fv) {
	if (fv->tiles) {
		double side = tile_side(fv);
		c8ui_list_set_mode(fv->list, C8UI_LIST_GRID, side, side);
	} else {
		c8ui_list_set_mode(fv->list, C8UI_LIST_SPANS, fv->width, UNIT);
	}
	/* A grid fills as many across as fit: held to its own width */
	fv->list->fill = fv->shape == SHAPE_PAGE && !fv->tiles;
	fv->list->fixed_width = fv->list->fill ? 0 : fv->width;
}

void view_set_tiles(struct feedview *fv, bool tiles) {
	fv->tiles = tiles;
	if (fv->list) {
		list_shape(fv);
		view_changed(fv);
		c8ui_widget_queue_layout(fv->list);
	}
}

static void opened(struct c8ui_widget *list, int index, void *data) {
	struct feedview *fv = data;
	struct sky_item *it = item_at(fv, index);
	if (it == NULL || it == &more_item) {
		return;
	}
	if (fv->tiles) {
		/* A picture opens the pictures, a video plays */
		c8ui_list_select(list, -1);
		struct sky_post *p = it->post;
		ui_activate(fv, it, p && p->n_images > 0 ? PART_MEDIA : p && p->video ?
			PART_VIDEO : PART_BODY, 0);
		return;
	}
	enum card_part part = PART_BODY;
	int sub = 0;
	double x, y;
	if (c8ui_list_open_point(list, &x, &y)) {
		part = card_hit(c8ui_widget_font(list), it,
			c8ui_list_get_item_rect(list, index), x, y, &sub);
	}
	/* A click opens; it isn't a choice to leave marked (the app bar
	 * still acts on what was clicked last). In a trail, a post opened
	 * beside it stays marked: it is the way to the next column. */
	struct sky_post *p = it->post;
	bool beside = part == PART_BODY && p && !it->focus &&
		it->kind != SKY_ITEM_ACTOR && it->kind != SKY_ITEM_NOTICE &&
		trail_has(fv);
	c8ui_list_select(list, beside ? index : -1);
	ui_activate(fv, it, part, sub);
}

static void selected(struct c8ui_widget *list, void *data) {
	struct sky_item *it = view_selected(data);
	ui_set_target(it ? it->post : NULL);
}

static void context(struct c8ui_widget *list, int index, double x, double y,
		void *data) {
	struct feedview *fv = data;
	struct sky_item *it = item_at(fv, index);
	if (it && it != &more_item) {
		c8ui_list_select(list, index);
		ui_set_target(it->post);
	} else {
		ui_set_target(NULL);
	}
	ui_show_bars();
}

static double width_for(enum view_shape shape, int *columns) {
	*columns = 1;
	if (shape == SHAPE_COLUMN) {
		/* Narrow, a page of the pivot the hub becomes: from its edge to
		 * the section's pad on the right */
		return g.narrow ? ui_width() - C8UI_HUB_NARROW_EDGE - NARROW_PAD :
			g.column_w;
	}
	if (shape == SHAPE_TRAIL) {
		return g.narrow ? ui_width() - 2 * NARROW_PAD : TRAIL_W;
	}
	/* One column, in reading order: a grid of them put a thread's
	 * answers and a feed's posts in no order anyone could follow */
	return g.narrow ? ui_width() - 2 * NARROW_PAD :
		fmin(ui_width() - PAGE_LEFT - PAGE_PAD, PAGE_COLUMN);
}

static void box_gone(struct c8ui_widget *w, void *data) {
	struct feedview *fv = data;
	if (fv->box == w) {
		fv->box = fv->list = fv->status = NULL;
	}
	view_unref(fv);
}

struct c8ui_widget *view_widget(struct feedview *fv, enum view_shape shape) {
	fv->shape = shape;
	fv->width = width_for(shape, &fv->columns);
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 8);
	box->fill = true;
	box->user_data = view_ref(fv);
	box->on_destroy = box_gone;
	fv->box = box;
	fv->status = c8ui_label_new("", C8UI_TEXT_BODY);
	c8ui_label_set_color(fv->status, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(box, fv->status);
	fv->list = c8ui_list_new(C8UI_LIST_SPANS, fv->width, UNIT, draw_item, fv);
	/* Words, photos and faces: drawn once, copied while it scrolls */
	c8ui_list_set_keep(fv->list, true);
	c8ui_list_set_spans(fv->list, spans, fv);
	c8ui_list_set_click_opens(fv->list, true);
	c8ui_list_on_open(fv->list, opened, fv);
	c8ui_list_on_select(fv->list, selected, fv);
	c8ui_list_on_context(fv->list, context, fv);
	list_shape(fv);
	c8ui_widget_add(box, fv->list);
	view_changed(fv);
	return box;
}

void view_resized(struct feedview *fv) {
	if (fv->list == NULL) {
		return;
	}
	int columns;
	double width = width_for(fv->shape, &columns);
	if (width == fv->width && columns == fv->columns) {
		return;
	}
	fv->width = width;
	fv->columns = columns;
	list_shape(fv);
	view_changed(fv);
	c8ui_widget_queue_layout(fv->list);
}

void views_resized(void) {
	for (guint i = 0; views && i < views->len; i++) {
		view_resized(views->pdata[i]);
	}
}

void views_redraw(void) {
	for (guint i = 0; views && i < views->len; i++) {
		view_changed(views->pdata[i]);
	}
}

void views_pictures(void) {
	for (guint i = 0; views && i < views->len; i++) {
		struct feedview *fv = views->pdata[i];
		if (fv->list) {
			/* What was drawn without its picture wasn't kept */
			c8ui_widget_queue_draw(fv->list);
		}
	}
}

void views_forget_account(void) {
	for (guint i = 0; views && i < views->len; i++) {
		struct feedview *fv = views->pdata[i];
		g_ptr_array_set_size(fv->items, 0);
		g_clear_pointer(&fv->cursor, g_free);
		g_clear_pointer(&fv->error, g_free);
		fv->serial++;
		fv->loading = fv->loaded = fv->ended = false;
		view_changed(fv);
	}
}

/* Loading */

static void finished(struct feedview *fv) {
	view_changed(fv);
	if (fv->on_loaded) {
		fv->on_loaded(fv, fv->on_loaded_data);
	}
}

/* The posts the notifications are about */
static void got_subjects(int status, struct json *json, const char *error,
		void *data) {
	struct request *rq = data;
	struct feedview *fv = rq->fv;
	if (status == 200 && rq->serial == fv->serial) {
		sky_notices_fill(json, fv->items);
		view_changed(fv);
	}
	view_unref(fv);
	g_free(rq);
}

static void ask_subjects(struct feedview *fv, GPtrArray *need) {
	for (guint at = 0; at < need->len; at += POSTS_AT_ONCE) {
		GString *call = g_string_new("app.bsky.feed.getPosts");
		for (guint i = at; i < need->len && i < at + POSTS_AT_ONCE; i++) {
			sky_query(call, "uris", need->pdata[i]);
		}
		struct request *rq = g_new0(struct request, 1);
		rq->fv = view_ref(fv);
		rq->serial = fv->serial;
		sky_get(call->str, got_subjects, rq);
		g_string_free(call, TRUE);
	}
}

static void seen(int status, struct json *json, const char *error,
		void *data) {
}

static void got(int status, struct json *json, const char *error,
		void *data) {
	struct request *rq = data;
	struct feedview *fv = rq->fv;
	bool more = rq->more;
	bool stale = rq->serial != fv->serial || (status == 0 && error == NULL);
	g_free(rq);
	if (stale) {
		view_unref(fv);
		return;
	}
	fv->loading = false;
	fv->loaded = true;
	g_clear_pointer(&fv->error, g_free);
	if (status != 200) {
		fv->error = g_strdup(error ? error : "Couldn't load this.");
		/* Not again and again as its end is drawn */
		fv->ended = more;
		finished(fv);
		view_unref(fv);
		return;
	}
	GPtrArray *fresh = g_ptr_array_new();
	GPtrArray *need = g_ptr_array_new_with_free_func(g_free);
	switch (fv->kind) {
	case VIEW_THREAD:
		sky_parse_thread(json, fresh);
		break;
	case VIEW_NOTICES:
		sky_parse_notices(json, fresh, need);
		break;
	case VIEW_PEOPLE:
		sky_parse_actors(json_get(json, "actors"), fresh);
		break;
	case VIEW_FOLLOWERS:
		sky_parse_actors(json_get(json, "followers"), fresh);
		break;
	case VIEW_FOLLOWS:
		sky_parse_actors(json_get(json, "follows"), fresh);
		break;
	default:
		sky_parse_feed(json, fresh);
		break;
	}
	if (!more) {
		g_ptr_array_set_size(fv->items, 0);
	}
	for (guint i = 0; i < fresh->len; i++) {
		g_ptr_array_add(fv->items, fresh->pdata[i]);
	}
	const char *cursor = json_str(json_get(json, "cursor"), NULL);
	g_free(fv->cursor);
	fv->cursor = g_strdup(cursor);
	fv->ended = cursor == NULL || fresh->len == 0 || fv->kind == VIEW_THREAD;
	g_ptr_array_unref(fresh);
	if (need->len) {
		ask_subjects(fv, need);
	}
	g_ptr_array_unref(need);
	if (fv->kind == VIEW_NOTICES && !more && fv->mark_seen && g.win) {
		/* They have been shown: the badge can go */
		GString *body = g_string_new("{\"seenAt\":");
		char *now = sky_now_iso();
		sky_json_str(body, now);
		g_string_append_c(body, '}');
		sky_post("app.bsky.notification.updateSeen", body->str, seen, NULL);
		g_string_free(body, TRUE);
		g_free(now);
		g.unread = 0;
	}
	finished(fv);
	view_unref(fv);
}

static void load(struct feedview *fv, bool more) {
	if (sky_me == NULL) {
		return;
	}
	GString *call = g_string_new(NULL);
	switch (fv->kind) {
	case VIEW_TIMELINE:
		g_string_assign(call, "app.bsky.feed.getTimeline?limit=" PAGE);
		break;
	case VIEW_FEED:
		g_string_assign(call, "app.bsky.feed.getFeed?limit=" PAGE);
		sky_query(call, "feed", fv->param);
		break;
	case VIEW_LIST:
		g_string_assign(call, "app.bsky.feed.getListFeed?limit=" PAGE);
		sky_query(call, "list", fv->param);
		break;
	case VIEW_AUTHOR:
		g_string_assign(call, "app.bsky.feed.getAuthorFeed?limit=" PAGE);
		sky_query(call, "actor", fv->param);
		sky_query(call, "filter", fv->filter ? fv->filter :
			"posts_and_author_threads");
		if (fv->filter == NULL) {
			g_string_append(call, "&includePins=true");
		}
		break;
	case VIEW_SEARCH:
		g_string_assign(call, "app.bsky.feed.searchPosts?limit=" PAGE);
		sky_query(call, "q", fv->param);
		sky_query(call, "sort", fv->filter ? fv->filter : "top");
		break;
	case VIEW_PEOPLE:
		g_string_assign(call, "app.bsky.actor.searchActors?limit=" PAGE);
		sky_query(call, "q", fv->param);
		break;
	case VIEW_FOLLOWERS:
		g_string_assign(call, "app.bsky.graph.getFollowers?limit=50");
		sky_query(call, "actor", fv->param);
		break;
	case VIEW_FOLLOWS:
		g_string_assign(call, "app.bsky.graph.getFollows?limit=50");
		sky_query(call, "actor", fv->param);
		break;
	case VIEW_NOTICES:
		g_string_assign(call,
			"app.bsky.notification.listNotifications?limit=" PAGE);
		break;
	case VIEW_THREAD:
		g_string_assign(call,
			"app.bsky.feed.getPostThread?depth=6&parentHeight=40");
		sky_query(call, "uri", fv->param);
		break;
	}
	if (more && fv->cursor) {
		sky_query(call, "cursor", fv->cursor);
	}
	if (!more) {
		fv->serial++;
	}
	fv->loading = true;
	fv->gen = sky_generation;
	struct request *rq = g_new0(struct request, 1);
	rq->fv = view_ref(fv);
	rq->serial = fv->serial;
	rq->more = more;
	sky_get(call->str, got, rq);
	g_string_free(call, TRUE);
	if (fv->items->len == 0) {
		view_changed(fv);
	}
}

void views_reload(int kind) {
	for (guint i = 0; views && i < views->len; i++) {
		struct feedview *fv = views->pdata[i];
		if (fv->list && (kind < 0 || (int)fv->kind == kind)) {
			load(fv, false);
		}
	}
}

void views_set_follow(const char *did, const char *uri) {
	for (guint i = 0; views && i < views->len; i++) {
		struct feedview *fv = views->pdata[i];
		bool changed = false;
		for (guint k = 0; k < fv->items->len; k++) {
			struct sky_item *it = fv->items->pdata[k];
			if (it->kind == SKY_ITEM_ACTOR && g_strcmp0(it->did, did) == 0) {
				g_free(it->follow_uri);
				it->follow_uri = g_strdup(uri);
				changed = true;
			}
		}
		if (changed) {
			view_changed(fv);
		}
	}
}

void views_remove_post(const char *uri) {
	for (guint i = 0; views && i < views->len; i++) {
		struct feedview *fv = views->pdata[i];
		bool changed = false;
		for (guint k = 0; k < fv->items->len;) {
			struct sky_item *it = fv->items->pdata[k];
			if (it->post && strcmp(it->post->uri, uri) == 0) {
				g_ptr_array_remove_index(fv->items, k);
				changed = true;
			} else {
				k++;
			}
		}
		if (changed) {
			view_changed(fv);
		}
	}
}

void view_reload(struct feedview *fv) {
	load(fv, false);
}

void view_ensure(struct feedview *fv) {
	if (!fv->loaded && !fv->loading) {
		load(fv, false);
	}
}
