/*
 * Writing a post: new, a reply or a quote, with up to four pictures, each
 * with words for those who can't see it. Pictures are made ready as they
 * are added (turned upright, no bigger than 2000 px, a JPEG under the
 * server's 2 MB, which also leaves the camera's place and time out of
 * them); sending looks the mentions up, uploads the pictures one by one
 * and then makes the record.
 */
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <string.h>
#include "app.h"

#define PICTURE_PX 2000
#define PICTURE_BYTES 1900000 // the server takes 2000000
#define ALT_MAX 2000

struct pic {
	struct composer *c;
	char *path; // the JPEG made of it, NULL until ready
	int width, height;
	bool failed;
	struct c8ui_widget *row, *image, *alt;
	char *blob; // its JSON once uploaded
};

struct composer {
	int refs;
	bool gone, sending, discard;
	struct sky_post *reply, *quote;
	struct c8ui_widget *page, *text, *count, *send, *add, *status, *pics_box;
	GPtrArray *pics;
	struct c8ui_file_dialog *picker;
	/* While sending */
	char *body;
	GHashTable *mentions; // handle -> DID
	int lookups; // still out
	guint uploading; // which picture
};

static struct composer *current; // the one on screen

static void pic_free(gpointer data) {
	struct pic *p = data;
	if (p->path) {
		g_unlink(p->path);
	}
	g_free(p->path);
	g_free(p->blob);
	g_free(p);
}

static void composer_unref(struct composer *c) {
	if (--c->refs > 0) {
		return;
	}
	sky_post_unref(c->reply);
	sky_post_unref(c->quote);
	g_ptr_array_unref(c->pics);
	g_free(c->body);
	if (c->mentions) {
		g_hash_table_unref(c->mentions);
	}
	g_free(c);
}

static void say(struct composer *c, const char *text) {
	if (c->gone) {
		return;
	}
	c8ui_label_set_text(c->status, text ? text : "");
	c8ui_widget_set_hidden(c->status, text == NULL);
}

static void update(struct composer *c) {
	if (c->gone) {
		return;
	}
	const char *text = c8ui_textview_get(c->text);
	int n = sky_graphemes(text);
	char count[32];
	g_snprintf(count, sizeof(count), "%d", SKY_TEXT_MAX - n);
	c8ui_label_set_text(c->count, count);
	c8ui_label_set_color(c->count, n > SKY_TEXT_MAX ? C8UI_COLOR_ACCENT :
		C8UI_COLOR_SECONDARY);
	bool waiting = false;
	for (guint i = 0; i < c->pics->len; i++) {
		waiting |= ((struct pic *)c->pics->pdata[i])->path == NULL;
	}
	char *trimmed = g_strstrip(g_strdup(text));
	bool something = trimmed[0] || c->pics->len;
	g_free(trimmed);
	c8ui_widget_set_disabled(c->send, c->sending || waiting || !something ||
		n > SKY_TEXT_MAX);
	c8ui_widget_set_disabled(c->add, c->sending ||
		c->pics->len >= SKY_IMAGES_MAX);
}

static void fail(struct composer *c, const char *error) {
	c->sending = false;
	say(c, error ? error : "That didn't work.");
	update(c);
}

/* Sending */

static void posted(int status, struct json *json, const char *error,
		void *data) {
	struct composer *c = data;
	if (status != 200) {
		fail(c, error);
		composer_unref(c);
		return;
	}
	bool reply = c->reply != NULL;
	c->sending = false;
	c->discard = true;
	if (!c->gone) {
		ui_pop();
	}
	views_reload(VIEW_TIMELINE);
	if (reply) {
		views_reload(VIEW_THREAD);
	}
	composer_unref(c);
}

static void make_record(struct composer *c) {
	GString *images = g_string_new(NULL);
	for (guint i = 0; i < c->pics->len; i++) {
		struct pic *p = c->pics->pdata[i];
		const char *alt = c->gone ? "" : c8ui_entry_get(p->alt);
		g_string_append_printf(images, "%s{\"image\":%s,\"aspectRatio\":"
			"{\"width\":%d,\"height\":%d},\"alt\":", i ? "," : "", p->blob,
			p->width, p->height);
		char *cut = g_utf8_substring(alt, 0, MIN(g_utf8_strlen(alt, -1),
			ALT_MAX));
		sky_json_str(images, cut);
		g_free(cut);
		g_string_append_c(images, '}');
	}
	char *record = sky_post_record(c->body, c->reply, c->quote, images->str,
		c->mentions);
	GString *body = g_string_new("{\"repo\":");
	sky_json_str(body, sky_me->did);
	g_string_append_printf(body, ",\"collection\":\"app.bsky.feed.post\","
		"\"record\":%s}", record);
	sky_post("com.atproto.repo.createRecord", body->str, posted, c);
	g_string_free(body, TRUE);
	g_string_free(images, TRUE);
	g_free(record);
}

static void upload_next(struct composer *c);

static void uploaded(int status, struct json *json, const char *error,
		void *data) {
	struct composer *c = data;
	const struct json *blob = json_get(json, "blob");
	if (status != 200 || blob == NULL) {
		fail(c, error ? error : "A picture couldn't be sent.");
		composer_unref(c);
		return;
	}
	struct pic *p = c->pics->pdata[c->uploading];
	g_free(p->blob);
	p->blob = json_dump(blob);
	c->uploading++;
	upload_next(c);
}

static void upload_next(struct composer *c) {
	if (c->uploading < c->pics->len) {
		struct pic *p = c->pics->pdata[c->uploading];
		char *text = g_strdup_printf("Sending picture %u of %u…",
			c->uploading + 1, c->pics->len);
		say(c, text);
		g_free(text);
		sky_upload(p->path, "image/jpeg", uploaded, c);
		return;
	}
	say(c, "Posting…");
	make_record(c);
}

struct lookup {
	struct composer *c;
	char *handle;
};

static void looked_up(int status, struct json *json, const char *error,
		void *data) {
	struct lookup *l = data;
	struct composer *c = l->c;
	const char *did = json_str(json_get(json, "did"), NULL);
	if (status == 200 && did) {
		g_hash_table_insert(c->mentions, l->handle, g_strdup(did));
	} else {
		g_free(l->handle); // no such person: it stays plain words
	}
	g_free(l);
	if (--c->lookups == 0) {
		if (status == 0 && error == NULL) {
			fail(c, NULL); // the account changed under it
			composer_unref(c);
		} else {
			upload_next(c);
		}
	}
}

static void send(struct c8ui_widget *w, void *data) {
	struct composer *c = data;
	if (c->sending || c->gone || sky_me == NULL) {
		return;
	}
	g_free(c->body);
	c->body = g_strstrip(g_strdup(c8ui_textview_get(c->text)));
	if (c->body[0] == '\0' && c->pics->len == 0) {
		return;
	}
	c->sending = true;
	c->uploading = 0;
	c->refs++; // until it is posted or fails
	say(c, "Posting…");
	update(c);
	if (c->mentions) {
		g_hash_table_unref(c->mentions);
	}
	c->mentions = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		g_free);
	GPtrArray *handles = sky_mentions_in(c->body);
	c->lookups = (int)handles->len;
	for (guint i = 0; i < handles->len; i++) {
		struct lookup *l = g_new0(struct lookup, 1);
		l->c = c;
		l->handle = g_strdup(handles->pdata[i]);
		GString *call = g_string_new("com.atproto.identity.resolveHandle");
		sky_query(call, "handle", l->handle);
		sky_get(call->str, looked_up, l);
		g_string_free(call, TRUE);
	}
	if (handles->len == 0) {
		upload_next(c);
	}
	g_ptr_array_unref(handles);
}

/* Pictures */

struct prepared {
	char *path;
	int width, height;
	GdkPixbuf *thumb;
};

static void prepared_free(gpointer data) {
	struct prepared *r = data;
	g_free(r->path);
	g_clear_object(&r->thumb);
	g_free(r);
}

/* On a thread: the picture as a JPEG the server will take */
static void prepare(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	const char *src = data;
	GdkPixbuf *loaded = gdk_pixbuf_new_from_file(src, NULL);
	if (loaded == NULL) {
		g_task_return_pointer(task, NULL, NULL);
		return;
	}
	GdkPixbuf *pb = gdk_pixbuf_apply_embedded_orientation(loaded);
	g_object_unref(loaded);
	/* On white: a JPEG has nothing see-through */
	if (gdk_pixbuf_get_has_alpha(pb)) {
		GdkPixbuf *flat = gdk_pixbuf_composite_color_simple(pb,
			gdk_pixbuf_get_width(pb), gdk_pixbuf_get_height(pb),
			GDK_INTERP_NEAREST, 255, 64, 0xffffff, 0xffffff);
		g_object_unref(pb);
		pb = flat;
	}
	char *dir = sky_cache_path("upload");
	g_mkdir_with_parents(dir, 0700);
	char *name = g_strdup_printf("%08x%08x.jpg", g_random_int(), g_random_int());
	char *path = g_build_filename(dir, name, NULL);
	g_free(name);
	g_free(dir);
	double limit = PICTURE_PX;
	bool ok = false;
	int w = 0, h = 0;
	for (int round = 0; round < 6 && !ok; round++) {
		w = gdk_pixbuf_get_width(pb);
		h = gdk_pixbuf_get_height(pb);
		double k = MIN(1.0, limit / MAX(w, h));
		w = MAX(1, (int)(w * k));
		h = MAX(1, (int)(h * k));
		GdkPixbuf *scaled = k < 1 ? gdk_pixbuf_scale_simple(pb, w, h,
			GDK_INTERP_BILINEAR) : g_object_ref(pb);
		static const char *const qualities[] = { "90", "80", "70" };
		for (int q = 0; q < 3 && !ok; q++) {
			GStatBuf st;
			if (gdk_pixbuf_save(scaled, path, "jpeg", NULL, "quality",
					qualities[q], NULL) && g_stat(path, &st) == 0) {
				ok = st.st_size <= PICTURE_BYTES;
			}
		}
		g_object_unref(scaled);
		limit *= 0.8; // still too big: smaller
	}
	if (!ok) {
		g_unlink(path);
		g_free(path);
		g_object_unref(pb);
		g_task_return_pointer(task, NULL, NULL);
		return;
	}
	struct prepared *r = g_new0(struct prepared, 1);
	r->path = path;
	r->width = w;
	r->height = h;
	double tk = 192.0 / MAX(w, h);
	r->thumb = gdk_pixbuf_scale_simple(pb, MAX(1, (int)(w * tk)),
		MAX(1, (int)(h * tk)), GDK_INTERP_BILINEAR);
	g_object_unref(pb);
	g_task_return_pointer(task, r, prepared_free);
}

static void pic_ready(GObject *source, GAsyncResult *res, gpointer data) {
	struct pic *p = data;
	struct composer *c = p->c;
	struct prepared *r = g_task_propagate_pointer(G_TASK(res), NULL);
	bool listed = g_ptr_array_find(c->pics, p, NULL);
	if (r == NULL || !listed || c->gone) {
		if (r) {
			g_unlink(r->path);
			prepared_free(r);
		}
		if (listed && !c->gone) {
			c8ui_widget_destroy(p->row);
			g_ptr_array_remove(c->pics, p);
			say(c, "That picture couldn't be read.");
			update(c);
		} else if (!listed) {
			pic_free(p); // taken off while it was being made
		}
		composer_unref(c);
		return;
	}
	p->path = g_strdup(r->path);
	p->width = r->width;
	p->height = r->height;
	if (r->thumb) {
		cairo_surface_t *s = c8ui_surface_from_pixels(
			gdk_pixbuf_read_pixels(r->thumb), gdk_pixbuf_get_width(r->thumb),
			gdk_pixbuf_get_height(r->thumb), gdk_pixbuf_get_rowstride(r->thumb),
			gdk_pixbuf_get_n_channels(r->thumb));
		c8ui_image_set(p->image, s);
		cairo_surface_destroy(s);
	}
	prepared_free(r);
	update(c);
	composer_unref(c);
}

static void pic_remove(struct c8ui_widget *w, void *data) {
	struct pic *p = data;
	struct composer *c = p->c;
	if (c->sending) {
		return;
	}
	c8ui_widget_destroy(p->row);
	guint at;
	if (g_ptr_array_find(c->pics, p, &at)) {
		/* Still being made: its thread's answer frees it */
		if (p->path == NULL) {
			g_ptr_array_steal_index(c->pics, at);
		} else {
			g_ptr_array_remove_index(c->pics, at);
		}
	}
	update(c);
}

static void add_picture(struct composer *c, const char *file) {
	struct pic *p = g_new0(struct pic, 1);
	p->c = c;
	p->row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	p->row->fill = true;
	p->image = c8ui_image_new(NULL, 96, 96);
	c8ui_widget_add(p->row, p->image);
	struct c8ui_widget *side = c8ui_box_new(C8UI_VERTICAL, 6);
	side->expand = true;
	p->alt = c8ui_entry_new("What it shows", "", NULL, NULL);
	c8ui_entry_set_placeholder(p->alt, "For people who can't see it");
	p->alt->fill = true;
	c8ui_widget_add(side, p->alt);
	c8ui_widget_add(side, c8ui_link_new("Take it off", pic_remove, p));
	c8ui_widget_add(p->row, side);
	c8ui_widget_add(c->pics_box, p->row);
	g_ptr_array_add(c->pics, p);
	c->refs++;
	GTask *task = g_task_new(NULL, NULL, pic_ready, p);
	g_task_set_task_data(task, g_strdup(file), g_free);
	g_task_run_in_thread(task, prepare);
	g_object_unref(task);
}

static void picked(char **uris, void *data) {
	struct composer *c = data;
	c->picker = NULL;
	for (int i = 0; uris && uris[i] && c->pics->len < SKY_IMAGES_MAX; i++) {
		char *file = g_filename_from_uri(uris[i], NULL, NULL);
		if (file) {
			add_picture(c, file);
			g_free(file);
		}
	}
	say(c, NULL);
	update(c);
}

static void add_clicked(struct c8ui_widget *w, void *data) {
	static const struct c8ui_file_filter filters[] = {
		{ "Pictures", "*.jpg;*.jpeg;*.png;*.webp;*.gif",
			"image/jpeg;image/png;image/webp;image/gif" },
		{ "All files", "*", NULL },
	};
	struct composer *c = data;
	if (c->picker || c->sending || g.win == NULL) {
		return;
	}
	c->picker = c8ui_file_open(g.win, &(struct c8ui_file_options){
		.title = "Add pictures",
		.accept = "Add",
		.multiple = true,
		.filters = filters,
		.filter_count = 2,
	}, picked, c);
}

/* The page */

static void text_changed(struct c8ui_widget *w, void *data) {
	update(data);
}

static void composer_gone(struct c8ui_widget *w, void *data) {
	struct composer *c = data;
	c->gone = true;
	if (c->picker) {
		c8ui_file_dialog_cancel(c->picker);
		c->picker = NULL;
	}
	if (current == c) {
		current = NULL;
	}
	composer_unref(c);
}

static void discard_answer(int choice, void *data) {
	struct composer *c = data;
	if (choice == 0 && !c->gone) {
		c->discard = true;
		ui_pop();
	}
	composer_unref(c);
}

bool compose_may_leave(void) {
	static const char *const buttons[] = { "Discard", "Keep writing" };
	struct composer *c = current;
	if (c == NULL || c->gone || c->discard) {
		return true;
	}
	if (c->sending) {
		return false; // a moment: it is on its way
	}
	char *text = g_strstrip(g_strdup(c8ui_textview_get(c->text)));
	bool empty = text[0] == '\0' && c->pics->len == 0;
	g_free(text);
	if (empty) {
		return true;
	}
	c->refs++;
	c8ui_dialog_show(g.root, "Discard this post?",
		"What you have written isn't kept.", buttons, 2, discard_answer, c);
	return false;
}

void open_compose(struct sky_post *reply, struct sky_post *quote,
		const char *text) {
	if (sky_me == NULL || current) {
		return;
	}
	struct composer *c = g_new0(struct composer, 1);
	c->refs = 1;
	c->reply = sky_post_ref(reply);
	c->quote = sky_post_ref(quote);
	c->pics = g_ptr_array_new_with_free_func(pic_free);
	current = c;

	struct c8ui_widget *body;
	c->page = page_new(reply ? "Reply" : quote ? "Quote" : "New post",
		&body);
	body->user_data = c;
	body->on_destroy = composer_gone;
	struct c8ui_widget *inner = c8ui_box_new(C8UI_VERTICAL, 12);
	inner->fill = true;
	ui_pad(inner, PAGE_LEFT, 8, PAGE_PAD, 40);
	struct c8ui_widget *col = c8ui_box_new(C8UI_VERTICAL, 12);
	col->fixed_width = FORM_W; // less in a narrow window
	struct sky_post *about = reply ? reply : quote;
	if (about) {
		char *who = g_strdup_printf(reply ? "Replying to %s" : "Quoting %s",
			sky_shown_name(about->did, about->name));
		c8ui_widget_add(col, c8ui_label_new(who, C8UI_TEXT_BODY_STRONG));
		g_free(who);
		if (about->text) {
			struct c8ui_widget *said = c8ui_label_new(
				sky_shown_text(about->text),
				C8UI_TEXT_BODY);
			c8ui_label_set_color(said, C8UI_COLOR_SECONDARY);
			c8ui_label_set_max_lines(said, 4);
			c8ui_widget_add(col, said);
		}
	}
	c->text = c8ui_textview_new(text ? text : "");
	c8ui_textview_set_framed(c->text, true);
	c8ui_textview_set_accepts_tab(c->text, false);
	c8ui_textview_set_placeholder(c->text, reply ? "Write your reply" :
		"What's up?");
	c8ui_textview_on_change(c->text, text_changed, c);
	c->text->fill = true;
	c->text->min_width = 200;
	struct c8ui_widget *box = c8ui_scroll_new(c->text);
	box->fill = true;
	box->fixed_height = 170;
	c8ui_widget_add(col, box);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(row, true);
	c->send = c8ui_button_new(reply ? "Reply" : "Post", send, c);
	c8ui_button_set_primary(c->send, true);
	c8ui_widget_add(row, c->send);
	c->add = c8ui_button_new("Add pictures", add_clicked, c);
	c8ui_widget_add(row, c->add);
	c->count = c8ui_label_new("300", C8UI_TEXT_BODY);
	c->count->align = C8UI_ALIGN_CENTER;
	c8ui_widget_set_tooltip(c->count, "Characters left");
	c8ui_widget_add(row, c->count);
	c8ui_widget_add(col, row);
	c->status = c8ui_label_new("", C8UI_TEXT_BODY);
	c8ui_widget_set_hidden(c->status, true);
	c8ui_widget_add(col, c->status);
	c->pics_box = c8ui_box_new(C8UI_VERTICAL, 12);
	c->pics_box->fill = true;
	c8ui_widget_add(col, c->pics_box);
	c8ui_widget_add(inner, col);
	struct c8ui_widget *scroll = c8ui_scroll_new(inner);
	scroll->fill = true;
	scroll->expand = true;
	c8ui_widget_add(body, scroll);
	ui_push(c->page);
	update(c);
	c8ui_widget_grab_focus(c->text);
}
