/* this sample is based off of the official ChakraCore examples */
#include "ChakraCore.h"
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <cstring>

#define FAIL_CHECK(cmd) \
  do { \
    JsErrorCode errCode = cmd; \
    if (errCode != JsNoError) { \
      printf("Error %d at '%s'\n", errCode, #cmd); \
      return 1; \
    } \
  } while(0)

using namespace std;

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 EVAL_FILE(path) {\
  JsValueRef filename; \
  JsValueRef result; \
  FAIL_CHECK(JsCreateString(path, strlen(path), &filename)); \
  size_t len; const char* script = read_file(path, &len);\
  JsValueRef src;\
  FAIL_CHECK(JsCreateExternalArrayBuffer((void*)script, len, nullptr, nullptr, &src));\
  FAIL_CHECK(JsRun(src, cookie++, filename, JsParseScriptAttributeNone, &result)); \
}


int main(int argc, char *argv[]) {
  JsRuntimeHandle runtime;
  JsContextRef context;
  JsValueRef result;
  size_t cookie = 0;

  FAIL_CHECK(JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime));
  FAIL_CHECK(JsCreateContext(runtime, &context));
  FAIL_CHECK(JsSetCurrentContext(context));

  JsValueRef global;
  FAIL_CHECK(JsGetGlobalObject(&global));

  EVAL_FILE("shim.min.js")

  EVAL_FILE("xlsx.full.min.js")

  JsValueRef buf_str;
  FAIL_CHECK(JsCreateString("buf", strlen("buf"), &buf_str));

  size_t len; char *buf = read_file(argv[1], &len);
  JsValueRef ab;
  FAIL_CHECK(JsCreateExternalArrayBuffer((void*)buf, len, nullptr, nullptr, &ab));
  FAIL_CHECK(JsObjectSetProperty(global, buf_str, ab, true));

  JsValueRef fname;
  FAIL_CHECK(JsCreateString("<script>", strlen("<script>"), &fname));

  const char* script_str =
    "var wb = XLSX.read(buf);"
    "var ws = wb.Sheets[wb.SheetNames[0]];"
    "XLSX.utils.sheet_to_csv(ws);";

  JsValueRef script;
  FAIL_CHECK(JsCreateExternalArrayBuffer((void*)script_str, (size_t)strlen(script_str), nullptr, nullptr, &script));
  FAIL_CHECK(JsRun(script, cookie++, fname, JsParseScriptAttributeNone, &result));

  free(buf);
  FAIL_CHECK(JsCopyString(result, nullptr, 0, &len));
  buf = (char*)malloc(len + 1);
  FAIL_CHECK(JsCopyString(result, buf, len + 1, nullptr));
  buf[len] = 0;

  printf("%s\n", buf);
  free(buf);

  FAIL_CHECK(JsSetCurrentContext(JS_INVALID_REFERENCE));
  FAIL_CHECK(JsDisposeRuntime(runtime));
  return 0;
}