/*
 * DiveLapse glue between libdivecomputer (compiled to WebAssembly) and the browser.
 *
 * libdivecomputer talks to a dive computer through an "iostream". Here that stream is a custom one whose
 * read and write calls go out to JavaScript (Module.dcio, see dcio.js), which does the actual Web Bluetooth
 * work (Web Bluetooth, or Web Serial for a cable). Both are asynchronous in the browser is asynchronous, so the calls use EM_ASYNC_JS and the module is built
 * with Asyncify: the C code waits as if the calls were blocking.
 *
 * Dives come back to JavaScript as JSON strings through Module.dcio.dive().
 */
#include <emscripten.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#include <libdivecomputer/context.h>
#include <libdivecomputer/descriptor.h>
#include <libdivecomputer/iterator.h>
#include <libdivecomputer/device.h>
#include <libdivecomputer/parser.h>
#include <libdivecomputer/custom.h>
#include <libdivecomputer/ble.h>
#include <libdivecomputer/version.h>

/* ---------- calls out to JavaScript ---------- */
/* read: bytes read, -1 timeout, -2 input/output error, -3 cancelled */
EM_ASYNC_JS(int, js_read, (unsigned char *buf, int size, int timeout), { return await Module.dcio.read(buf, size, timeout); });
EM_ASYNC_JS(int, js_write, (const unsigned char *buf, int size), { return await Module.dcio.write(buf, size); });
EM_ASYNC_JS(int, js_poll, (int timeout), { return await Module.dcio.poll(timeout); });
EM_ASYNC_JS(int, js_sleep, (int ms), { await new Promise(r => setTimeout(r, ms)); return 0; });
EM_ASYNC_JS(int, js_char_read, (const char *uuid, unsigned char *buf, int size), { return await Module.dcio.charRead(UTF8ToString(uuid), buf, size); });
EM_ASYNC_JS(int, js_char_write, (const char *uuid, const unsigned char *buf, int size), { return await Module.dcio.charWrite(UTF8ToString(uuid), buf, size); });
/* a serial cable: line settings and the DTR, RTS and break lines (kind 0 break, 1 DTR, 2 RTS); nothing to do over Bluetooth */
EM_ASYNC_JS(int, js_configure, (int baud, int bits, int parity, int stop, int flow), {
	return Module.dcio.configure ? await Module.dcio.configure(baud, bits, parity, stop, flow) : 0; });
EM_ASYNC_JS(int, js_signal, (int kind, int value), { return Module.dcio.signal ? await Module.dcio.signal(kind, value) : 0; });
EM_JS(int, js_available, (), { return Module.dcio.available(); });
EM_JS(void, js_purge, (), { Module.dcio.purge(); });
EM_JS(int, js_cancelled, (), { return Module.dcio.cancelled ? 1 : 0; });
EM_JS(int, js_name, (char *buf, int size), { const n = Module.dcio.name || ""; if (!n) return -1; stringToUTF8(n, buf, size); return 0; });
EM_JS(int, js_code_get, (unsigned char *buf, int size), { return Module.dcio.codeGet(buf, size); });
EM_JS(void, js_code_set, (const unsigned char *buf, int size), { Module.dcio.codeSet(buf, size); });
EM_JS(void, js_log, (int level, const char *msg), { Module.dcio.libLog(level, UTF8ToString(msg)); });
EM_JS(void, js_event, (const char *json), { Module.dcio.event(JSON.parse(UTF8ToString(json))); });
EM_JS(void, js_dive, (const char *json), { Module.dcio.dive(UTF8ToString(json)); });

/* ---------- a small growable string for JSON ---------- */
typedef struct { char *s; size_t n, cap; } buf_t;
static void bput (buf_t *b, const char *fmt, ...)
{
	va_list ap;
	for (;;) {
		va_start (ap, fmt);
		int need = vsnprintf (b->s ? b->s + b->n : NULL, b->s ? b->cap - b->n : 0, fmt, ap);
		va_end (ap);
		if (need < 0) return;
		if (b->s && b->n + need < b->cap) { b->n += need; return; }
		size_t cap = (b->cap ? b->cap : 1024);
		while (cap <= b->n + need) cap *= 2;
		char *s = realloc (b->s, cap);
		if (!s) return;
		if (!b->s) s[0] = 0;
		b->s = s; b->cap = cap;
	}
}
static void bstr (buf_t *b, const char *s)
{
	bput (b, "\"");
	for (; s && *s; s++) {
		unsigned char c = (unsigned char) *s;
		if (c == '"' || c == '\\') bput (b, "\\%c", c);
		else if (c < 0x20) bput (b, "\\u%04x", c);
		else bput (b, "%c", c);
	}
	bput (b, "\"");
}
static void bhex (buf_t *b, const unsigned char *d, unsigned int n)
{
	bput (b, "\"");
	for (unsigned int i = 0; i < n; i++) bput (b, "%02x", d[i]);
	bput (b, "\"");
}

/* ---------- the custom stream ---------- */
static int io_timeout = -1;

static dc_status_t st (int n)
{
	if (n >= 0) return DC_STATUS_SUCCESS;
	if (n == -1) return DC_STATUS_TIMEOUT;
	if (n == -3) return DC_STATUS_CANCELLED;
	return DC_STATUS_IO;
}
static dc_status_t cb_set_timeout (void *u, int timeout) { io_timeout = timeout; return DC_STATUS_SUCCESS; }
static dc_status_t cb_set_break (void *u, unsigned int v) { return st (js_signal (0, (int) v)); }
static dc_status_t cb_set_dtr (void *u, unsigned int v) { return st (js_signal (1, (int) v)); }
static dc_status_t cb_set_rts (void *u, unsigned int v) { return st (js_signal (2, (int) v)); }
static dc_status_t cb_get_lines (void *u, unsigned int *v) { *v = 0; return DC_STATUS_SUCCESS; }
static dc_status_t cb_available (void *u, size_t *v) { *v = (size_t) js_available (); return DC_STATUS_SUCCESS; }
static dc_status_t cb_configure (void *u, unsigned int baud, unsigned int bits, dc_parity_t p, dc_stopbits_t s, dc_flowcontrol_t f)
{
	return st (js_configure ((int) baud, (int) bits, (int) p, (int) s, (int) f));
}
static dc_status_t cb_poll (void *u, int timeout) { return st (js_poll (timeout)); }
static dc_status_t cb_read (void *u, void *data, size_t size, size_t *actual)
{
	int n = js_read (data, (int) size, io_timeout);
	if (actual) *actual = n > 0 ? (size_t) n : 0;
	return st (n);
}
static dc_status_t cb_write (void *u, const void *data, size_t size, size_t *actual)
{
	int n = js_write (data, (int) size);
	if (actual) *actual = n > 0 ? (size_t) n : 0;
	return st (n);
}
static dc_status_t cb_ioctl (void *u, unsigned int request, void *data, size_t size)
{
	switch (request) {
	case DC_IOCTL_BLE_GET_NAME:
		return js_name (data, (int) size) == 0 ? DC_STATUS_SUCCESS : DC_STATUS_UNSUPPORTED;
	case DC_IOCTL_BLE_GET_ACCESSCODE: {
		int n = js_code_get (data, (int) size);
		return n < 0 ? DC_STATUS_UNSUPPORTED : DC_STATUS_SUCCESS;
	}
	case DC_IOCTL_BLE_SET_ACCESSCODE:
		js_code_set (data, (int) size);
		return DC_STATUS_SUCCESS;
	case DC_IOCTL_BLE_CHARACTERISTIC_READ:
	case DC_IOCTL_BLE_CHARACTERISTIC_WRITE: {
		if (size < sizeof (dc_ble_uuid_t)) return DC_STATUS_INVALIDARGS;
		char uuid[DC_BLE_UUID_SIZE];
		dc_ble_uuid2str (data, uuid, sizeof uuid);
		unsigned char *rest = (unsigned char *) data + sizeof (dc_ble_uuid_t);
		int len = (int) (size - sizeof (dc_ble_uuid_t));
		int n = request == DC_IOCTL_BLE_CHARACTERISTIC_READ ? js_char_read (uuid, rest, len) : js_char_write (uuid, rest, len);
		return st (n);
	}
	default:
		return DC_STATUS_UNSUPPORTED;
	}
}
static dc_status_t cb_flush (void *u) { return DC_STATUS_SUCCESS; }
static dc_status_t cb_purge (void *u, dc_direction_t d) { js_purge (); return DC_STATUS_SUCCESS; }
static dc_status_t cb_sleep (void *u, unsigned int ms) { js_sleep ((int) ms); return DC_STATUS_SUCCESS; }
static dc_status_t cb_close (void *u) { return DC_STATUS_SUCCESS; }

static const dc_custom_cbs_t cbs = {
	cb_set_timeout, cb_set_break, cb_set_dtr, cb_set_rts, cb_get_lines, cb_available, cb_configure, cb_poll,
	cb_read, cb_write, cb_ioctl, cb_flush, cb_purge, cb_sleep, cb_close,
};

/* ---------- logging and events ---------- */
static void logfunc (dc_context_t *ctx, dc_loglevel_t level, const char *file, unsigned int line, const char *fn, const char *msg, void *u)
{
	js_log ((int) level, msg);
}

static void on_event (dc_device_t *dev, dc_event_type_t event, const void *data, void *u)
{
	buf_t b = {0};
	if (event == DC_EVENT_PROGRESS) {
		const dc_event_progress_t *p = data;
		bput (&b, "{\"type\":\"progress\",\"current\":%u,\"maximum\":%u}", p->current, p->maximum);
	} else if (event == DC_EVENT_DEVINFO) {
		const dc_event_devinfo_t *d = data;
		bput (&b, "{\"type\":\"devinfo\",\"model\":%u,\"firmware\":%u,\"serial\":%u}", d->model, d->firmware, d->serial);
	} else if (event == DC_EVENT_WAITING) {
		bput (&b, "{\"type\":\"waiting\"}");
	} else return;
	js_event (b.s);
	free (b.s);
}

static int on_cancel (void *u) { return js_cancelled (); }

/* ---------- dives ---------- */
typedef struct { buf_t *b; unsigned int time; int first; double lastTemp; } samples_t;

static void on_sample (dc_sample_type_t type, const dc_sample_value_t *v, void *u)
{
	samples_t *s = u;
	/* one [seconds, depth] pair per depth reading; temperature goes in a third slot when it changes */
	if (type == DC_SAMPLE_TIME) s->time = v->time / 1000;
	else if (type == DC_SAMPLE_DEPTH) {
		bput (s->b, "%s[%u,%.2f]", s->first ? "" : ",", s->time, v->depth);
		s->first = 0;
	} else if (type == DC_SAMPLE_TEMPERATURE && !s->first) {
		/* rewrite the last pair as a triple */
		if (s->b->n && s->b->s[s->b->n - 1] == ']' && v->temperature != s->lastTemp) {
			s->b->n--; s->b->s[s->b->n] = 0;
			bput (s->b, ",%.1f]", v->temperature);
			s->lastTemp = v->temperature;
		}
	}
}

typedef struct { dc_device_t *dev; int count; } run_t;

static int on_dive (const unsigned char *data, unsigned int size, const unsigned char *fp, unsigned int fsize, void *u)
{
	run_t *r = u;
	dc_parser_t *p = NULL;
	buf_t b = {0};
	r->count++;
	bput (&b, "{\"fingerprint\":");
	bhex (&b, fp, fsize);
	if (dc_parser_new (&p, r->dev, data, size) != DC_STATUS_SUCCESS) {
		bput (&b, ",\"error\":\"parse\"}");
		js_dive (b.s); free (b.s);
		return 1;
	}
	dc_datetime_t dt = {0};
	if (dc_parser_get_datetime (p, &dt) == DC_STATUS_SUCCESS)
		bput (&b, ",\"date\":\"%04d-%02d-%02d\",\"time\":\"%02d:%02d:%02d\",\"tz\":%d", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
			dt.timezone == DC_TIMEZONE_NONE ? -99999 : dt.timezone);
	unsigned int divetime = 0; double d = 0;
	if (dc_parser_get_field (p, DC_FIELD_DIVETIME, 0, &divetime) == DC_STATUS_SUCCESS) bput (&b, ",\"divetime\":%u", divetime);
	if (dc_parser_get_field (p, DC_FIELD_MAXDEPTH, 0, &d) == DC_STATUS_SUCCESS) bput (&b, ",\"maxdepth\":%.2f", d);
	if (dc_parser_get_field (p, DC_FIELD_AVGDEPTH, 0, &d) == DC_STATUS_SUCCESS) bput (&b, ",\"avgdepth\":%.2f", d);
	if (dc_parser_get_field (p, DC_FIELD_TEMPERATURE_MINIMUM, 0, &d) == DC_STATUS_SUCCESS) bput (&b, ",\"tempmin\":%.1f", d);
	if (dc_parser_get_field (p, DC_FIELD_TEMPERATURE_SURFACE, 0, &d) == DC_STATUS_SUCCESS) bput (&b, ",\"tempsurface\":%.1f", d);
	dc_divemode_t mode;
	if (dc_parser_get_field (p, DC_FIELD_DIVEMODE, 0, &mode) == DC_STATUS_SUCCESS) bput (&b, ",\"mode\":%d", (int) mode);
	samples_t s = { &b, 0, 1, -1000 };
	bput (&b, ",\"samples\":[");
	dc_parser_samples_foreach (p, on_sample, &s);
	bput (&b, "]}");
	dc_parser_destroy (p);
	js_dive (b.s);
	free (b.s);
	return 1;
}

/* ---------- exported to the page ---------- */
static dc_context_t *ctx_new (int level)
{
	dc_context_t *ctx = NULL;
	if (dc_context_new (&ctx) != DC_STATUS_SUCCESS) return NULL;
	dc_context_set_loglevel (ctx, (dc_loglevel_t) level);
	dc_context_set_logfunc (ctx, logfunc, NULL);
	return ctx;
}

EMSCRIPTEN_KEEPALIVE const char *dcw_version (void) { return DC_VERSION; }

/* Every dive computer the library knows that can use the given transports (bit mask, e.g. DC_TRANSPORT_BLE).
   With a Bluetooth name, only the models whose name filter accepts it. Returns JSON; the caller frees it. */
EMSCRIPTEN_KEEPALIVE char *dcw_list (unsigned int transports, const char *name)
{
	dc_context_t *ctx = ctx_new (DC_LOGLEVEL_ERROR);
	dc_iterator_t *it = NULL;
	dc_descriptor_t *d = NULL;
	buf_t b = {0};
	int first = 1;
	bput (&b, "[");
	if (ctx && dc_descriptor_iterator_new (&it, ctx) == DC_STATUS_SUCCESS) {
		while (dc_iterator_next (it, &d) == DC_STATUS_SUCCESS) {
			unsigned int t = dc_descriptor_get_transports (d);
			int ok = (t & transports) != 0;
			if (ok && name && *name) ok = dc_descriptor_filter (d, DC_TRANSPORT_BLE, name);
			if (ok) {
				bput (&b, "%s{\"vendor\":", first ? "" : ",");
				bstr (&b, dc_descriptor_get_vendor (d));
				bput (&b, ",\"product\":");
				bstr (&b, dc_descriptor_get_product (d));
				bput (&b, ",\"model\":%u,\"transports\":%u}", dc_descriptor_get_model (d), t);
				first = 0;
			}
			dc_descriptor_free (d);
		}
		dc_iterator_free (it);
	}
	bput (&b, "]");
	if (ctx) dc_context_free (ctx);
	return b.s;
}

/* Download from the computer that Module.dcio is connected to. vendor and product pick the model (from dcw_list).
   fingerprint (hex, may be empty) stops at the last dive already downloaded. Returns a dc_status_t (0 is success). */
EMSCRIPTEN_KEEPALIVE int dcw_download (const char *vendor, const char *product, unsigned int transport, const char *fphex, int loglevel)
{
	dc_context_t *ctx = ctx_new (loglevel);
	dc_iterator_t *it = NULL;
	dc_descriptor_t *d = NULL, *pick = NULL;
	dc_iostream_t *io = NULL;
	dc_device_t *dev = NULL;
	dc_status_t rc;
	if (!ctx) return DC_STATUS_NOMEMORY;

	if (dc_descriptor_iterator_new (&it, ctx) == DC_STATUS_SUCCESS) {
		while (dc_iterator_next (it, &d) == DC_STATUS_SUCCESS) {
			if (!pick && strcmp (dc_descriptor_get_vendor (d), vendor) == 0 && strcmp (dc_descriptor_get_product (d), product) == 0
				&& (dc_descriptor_get_transports (d) & transport)) pick = d;
			else dc_descriptor_free (d);
		}
		dc_iterator_free (it);
	}
	if (!pick) { dc_context_free (ctx); return DC_STATUS_UNSUPPORTED; }

	io_timeout = -1;
	rc = dc_custom_open (&io, ctx, (dc_transport_t) transport, &cbs, NULL);
	if (rc == DC_STATUS_SUCCESS) rc = dc_device_open (&dev, ctx, pick, io);
	if (rc == DC_STATUS_SUCCESS) {
		run_t r = { dev, 0 };
		dc_device_set_events (dev, DC_EVENT_WAITING | DC_EVENT_PROGRESS | DC_EVENT_DEVINFO, on_event, NULL);
		dc_device_set_cancel (dev, on_cancel, NULL);
		size_t n = fphex ? strlen (fphex) / 2 : 0;
		if (n) {
			unsigned char *fp = malloc (n);
			for (size_t i = 0; i < n; i++) { unsigned int v; sscanf (fphex + 2 * i, "%2x", &v); fp[i] = (unsigned char) v; }
			dc_device_set_fingerprint (dev, fp, (unsigned int) n);
			free (fp);
		}
		rc = dc_device_foreach (dev, on_dive, &r);
	}
	if (dev) dc_device_close (dev);
	if (io) dc_iostream_close (io);
	dc_descriptor_free (pick);
	dc_context_free (ctx);
	return (int) rc;
}

EMSCRIPTEN_KEEPALIVE void dcw_free (void *p) { free (p); }
