/*
 * Decoding and encoding through glycin, off the main loop: the copies
 * crop saves, the pictures Set as makes for Start and the lock screen,
 * and the tile provider's small ones. glycin's encoders run sandboxed
 * like its decoders. What is written loses the original's metadata (the
 * camera's details); the picture is already turned as its EXIF said.
 */
#include <math.h>
#include <string.h>
#include <glib/gstdio.h>
#include <glycin.h>
#include "encode.h"

#if G_BYTE_ORDER == G_LITTLE_ENDIAN
#define CAIRO_LAYOUT GLY_MEMORY_SELECTION_B8G8R8A8_PREMULTIPLIED
#else
#define CAIRO_LAYOUT GLY_MEMORY_SELECTION_A8R8G8B8_PREMULTIPLIED
#endif

#define JPEG_QUALITY 92

cairo_surface_t *ph_decode(const char *file, GError **err) {
	GFile *f = strstr(file, "://") ? g_file_new_for_uri(file) :
		g_file_new_for_path(file);
	GlyLoader *loader = gly_loader_new(f);
	g_object_unref(f);
	gly_loader_set_accepted_memory_formats(loader, CAIRO_LAYOUT);
	GlyImage *image = gly_loader_load(loader, err);
	g_object_unref(loader);
	if (image == NULL) {
		return NULL;
	}
	GlyFrame *frame = gly_image_next_frame(image, err);
	g_object_unref(image);
	if (frame == NULL) {
		return NULL;
	}
	int w = gly_frame_get_width(frame), h = gly_frame_get_height(frame);
	int stride = gly_frame_get_stride(frame);
	GBytes *bytes = gly_frame_get_buf_bytes(frame);
	gsize len;
	const guint8 *data = g_bytes_get_data(bytes, &len);
	cairo_surface_t *s = NULL;
	if (w > 0 && h > 0 && stride >= w * 4 &&
			len >= (gsize)stride * (h - 1) + w * 4) {
		/* A copy of our own: the frame goes now */
		s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
		guint8 *dst = cairo_image_surface_get_data(s);
		int dstride = cairo_image_surface_get_stride(s);
		for (int y = 0; y < h; y++) {
			memcpy(dst + (gsize)y * dstride, data + (gsize)y * stride,
				(gsize)w * 4);
		}
		cairo_surface_mark_dirty(s);
	}
	g_object_unref(frame);
	if (s == NULL) {
		g_set_error_literal(err, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
			"The picture came out empty");
	}
	return s;
}

cairo_surface_t *ph_shrink(cairo_surface_t *s, int max_side) {
	int w = cairo_image_surface_get_width(s);
	int h = cairo_image_surface_get_height(s);
	if (max_side <= 0 || (w <= max_side && h <= max_side)) {
		return cairo_surface_reference(s);
	}
	double k = (double)max_side / MAX(w, h);
	int nw = MAX(1, (int)lround(w * k)), nh = MAX(1, (int)lround(h * k));
	cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		nw, nh);
	cairo_t *cr = cairo_create(out);
	cairo_scale(cr, (double)nw / w, (double)nh / h);
	cairo_set_source_surface(cr, s, 0, 0);
	/* GOOD averages only a little when shrinking a lot; BEST is a proper
	 * box filter, and this is off the main loop */
	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_BEST);
	cairo_paint(cr);
	cairo_destroy(cr);
	return out;
}

static bool opaque(cairo_surface_t *s) {
	int w = cairo_image_surface_get_width(s);
	int h = cairo_image_surface_get_height(s);
	int stride = cairo_image_surface_get_stride(s);
	const guint8 *data = cairo_image_surface_get_data(s);
	for (int y = 0; y < h; y++) {
		const guint32 *row = (const guint32 *)(data + (gsize)y * stride);
		for (int x = 0; x < w; x++) {
			if ((row[x] >> 24) != 0xff) {
				return false;
			}
		}
	}
	return true;
}

/* cairo's premultiplied native-endian ARGB as the plain bytes encoders
 * take: RGB (what shows over black) or RGBA */
static GBytes *plain_pixels(cairo_surface_t *s, bool alpha) {
	cairo_surface_flush(s);
	int w = cairo_image_surface_get_width(s);
	int h = cairo_image_surface_get_height(s);
	int stride = cairo_image_surface_get_stride(s);
	const guint8 *data = cairo_image_surface_get_data(s);
	int n = alpha ? 4 : 3;
	guint8 *out = g_malloc((gsize)w * h * n);
	guint8 *o = out;
	for (int y = 0; y < h; y++) {
		const guint32 *row = (const guint32 *)(data + (gsize)y * stride);
		for (int x = 0; x < w; x++) {
			guint32 p = row[x];
			guint a = p >> 24, r = (p >> 16) & 0xff, g = (p >> 8) & 0xff,
				b = p & 0xff;
			if (alpha && a > 0 && a < 255) {
				r = (r * 255 + a / 2) / a;
				g = (g * 255 + a / 2) / a;
				b = (b * 255 + a / 2) / a;
			}
			*o++ = r;
			*o++ = g;
			*o++ = b;
			if (alpha) {
				*o++ = a;
			}
		}
	}
	return g_bytes_new_take(out, (gsize)w * h * n);
}

bool ph_can_encode(const char *mime) {
	if (mime == NULL) {
		return false;
	}
	GlyCreator *c = gly_creator_new(mime, NULL);
	if (c == NULL) {
		return false;
	}
	g_object_unref(c);
	return true;
}

GBytes *ph_encode(cairo_surface_t *s, const char *mime, GError **err) {
	GlyCreator *creator = gly_creator_new(mime, err);
	if (creator == NULL) {
		return NULL;
	}
	bool jpeg = strcmp(mime, "image/jpeg") == 0;
	bool alpha = !jpeg && !opaque(s);
	int w = cairo_image_surface_get_width(s);
	int h = cairo_image_surface_get_height(s);
	GBytes *pixels = plain_pixels(s, alpha);
	GlyNewFrame *frame = gly_creator_add_frame(creator, w, h,
		alpha ? GLY_MEMORY_R8G8B8A8 : GLY_MEMORY_R8G8B8, pixels, err);
	g_bytes_unref(pixels);
	GBytes *out = NULL;
	if (frame) {
		g_object_unref(frame);
		gly_creator_set_encoding_quality(creator, JPEG_QUALITY);
		GlyEncodedImage *enc = gly_creator_create(creator, err);
		if (enc) {
			out = gly_encoded_image_get_data(enc);
			g_object_unref(enc);
		}
	}
	g_object_unref(creator);
	return out;
}

/* Saving on a thread */

struct save {
	cairo_surface_t *part;
	int max_side;
	char *mime, *path, *error;
	ph_saved_fn done;
	void *data;
};

static void save_free(gpointer p) {
	struct save *sv = p;
	cairo_surface_destroy(sv->part);
	g_free(sv->mime);
	g_free(sv->path);
	g_free(sv->error);
	g_free(sv);
}

static void save_thread(GTask *task, gpointer src, gpointer data,
		GCancellable *cancel) {
	struct save *sv = data;
	cairo_surface_t *s = ph_shrink(sv->part, sv->max_side);
	GError *err = NULL;
	GBytes *bytes = ph_encode(s, sv->mime, &err);
	cairo_surface_destroy(s);
	if (bytes) {
		char *dir = g_path_get_dirname(sv->path);
		g_mkdir_with_parents(dir, 0700);
		g_free(dir);
		gsize len;
		const char *b = g_bytes_get_data(bytes, &len);
		/* By rename: whoever watches it never reads half */
		g_file_set_contents(sv->path, b, len, &err);
		g_bytes_unref(bytes);
	}
	if (err) {
		sv->error = g_strdup(err->message);
		g_error_free(err);
	}
	g_task_return_boolean(task, TRUE);
}

static void saved(GObject *src, GAsyncResult *res, gpointer data) {
	struct save *sv = g_task_get_task_data(G_TASK(res));
	if (sv->done) {
		sv->done(sv->error, sv->data);
	}
}

void ph_save(cairo_surface_t *s, int x, int y, int w, int h, int max_side,
		const char *mime, const char *path, ph_saved_fn done, void *data) {
	struct save *sv = g_new0(struct save, 1);
	/* The part, copied here: the viewer goes on drawing s meanwhile */
	sv->part = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
	cairo_t *cr = cairo_create(sv->part);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_set_source_surface(cr, s, -x, -y);
	cairo_paint(cr);
	cairo_destroy(cr);
	sv->max_side = max_side;
	sv->mime = g_strdup(mime);
	sv->path = g_strdup(path);
	sv->done = done;
	sv->data = data;
	GTask *task = g_task_new(NULL, NULL, saved, NULL);
	g_task_set_task_data(task, sv, save_free);
	g_task_run_in_thread(task, save_thread);
	g_object_unref(task);
}
