#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#include "quickjs.h"

static char *read_file(const char *filename, size_t *sz) {
	FILE *f = fopen(filename, "rb");
	if(!f) return NULL;
	long fsize; { fseek(f, 0, SEEK_END); fsize = ftell(f); fseek(f, 0, SEEK_SET); }
	char *buf = (char *)malloc(fsize * sizeof(char));
	*sz = fread((void *) buf, 1, fsize, f);
	fclose(f);
	return buf;
}

#define CLEANUP(v) { JS_FreeContext(ctx); JS_FreeRuntime(rt); return v; }
#define FREE(v) JS_FreeValue(ctx, v);
#define VALIDATE(v) { if(JS_IsException(v)) CLEANUP(1) }
#define VALINIT(xx,vv) \
  JSValue xx = vv;\
	VALIDATE(xx)
#define VALPROP(xx,vv,pp) VALINIT(xx, JS_GetPropertyStr(ctx, vv, pp))

int main(int argc, char *argv[]) {
	JSRuntime *rt = JS_NewRuntime();
	JSContext *ctx = JS_NewContext(rt);

	/* load library */
	{
		size_t len; char * buf = read_file("xlsx.full.min.js", &len);
		VALIDATE(JS_Eval(ctx, buf, len, "<input>", 0))
		free(buf);
	}

	VALINIT(global, JS_GetGlobalObject(ctx))
	VALPROP(XLSX, global, "XLSX");
	FREE(global)

	/* print version */
	{
		VALPROP(version, XLSX, "version")
		size_t vlen; const char *vers = JS_ToCStringLen(ctx, &vlen, version);
		printf("Version: %s\n", vers);
		FREE(version)
	}

	/* parse workbook */
	JSValue wb;
	{
		/* read file */
		size_t dlen; uint8_t * dbuf = (uint8_t *)read_file(argv[1], &dlen);

		/* load data into array buffer */
		JSValue ab = JS_NewArrayBuffer(ctx, dbuf, dlen, NULL, NULL, 0);
		{
			VALPROP(byteLen, ab, "byteLength")
			uint32_t byteLength; JS_ToUint32(ctx, &byteLength, byteLen);
			FREE(byteLen)
			printf("Size: %d\n", byteLength);
		}

		/* call XLSX.read(ab) */
		{
			VALPROP(XLSX_read, XLSX, "read");
			JSValue args[] = { ab };
			wb = JS_Call(ctx, XLSX_read, XLSX, 1, args);
			FREE(XLSX_read)
		}

		/* cleanup */
		FREE(ab)
		free(dbuf);
	}

	/* print CSV of first worksheet */
	{
		/* get first worksheet */
		JSValue ws;
		{
			/* get name of first sheet */
			const char *wsname;
			{
				JSValue SheetNames = JS_GetPropertyStr(ctx, wb, "SheetNames");
				JSValue Sheet1 = JS_GetPropertyStr(ctx, SheetNames, "0");
				size_t wslen; wsname = JS_ToCStringLen(ctx, &wslen, Sheet1);
				FREE(Sheet1)
				FREE(SheetNames)
			}
			printf("Worksheet Name: %s\n", wsname);

			/* get worksheet object */
			{
				VALPROP(Sheets, wb, "Sheets");
				ws = JS_GetPropertyStr(ctx, Sheets, wsname);
				FREE(Sheets)
			}
		}

		/* print CSV */
		{
			VALPROP(utils, XLSX, "utils")
			VALPROP(sheet_to_csv, utils, "sheet_to_csv")
			JSValue args[] = { ws };
			JSValue csv = JS_Call(ctx, sheet_to_csv, utils, 1, args);
			FREE(sheet_to_csv)
			FREE(utils)
			size_t csvlen; const char *csvstr = JS_ToCStringLen(ctx, &csvlen, csv);
			printf("%s\n", csvstr);
			FREE(csv)
		}

		FREE(ws)
	}

	FREE(wb)
	FREE(XLSX)
	CLEANUP(0)
}
