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

#include "jerryscript.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) - 1;
  fclose(f);
  return buf;
}

jerry_value_t eval_str(const char *code, size_t sz) {
  jerry_value_t parsed = jerry_parse(code, sz, NULL);
  if(jerry_value_is_error(parsed)) return parsed;

  jerry_value_t out = jerry_run(parsed);
  jerry_value_free(parsed);

  return out;
}

static jerry_value_t load_file(const char *filename) {
  size_t len; char *buf = read_file(filename, &len);
  if(!buf) return 0;

  jerry_value_t out = jerry_arraybuffer(len);
  jerry_arraybuffer_write(out, 0, (const uint8_t*)buf, len);
  return out;
}

char *pull_str(jerry_value_t str, size_t *sz) {
  jerry_size_t str_sz = jerry_string_size(str, JERRY_ENCODING_UTF8);
  jerry_char_t *buf = (jerry_char_t *)malloc(str_sz + 1);
  jerry_string_to_buffer(str, JERRY_ENCODING_UTF8, buf, str_sz + 1);
  *sz = str_sz;
  return (char *)buf;
}

int main (int argc, char **argv) {
  int res = 0;

  /* Initialize engine */
  jerry_init(JERRY_INIT_EMPTY);

  /* evaluate shim.min.js */
  {
    size_t sz; const jerry_char_t *script = (jerry_char_t *)read_file("shim.min.js", &sz);
    jerry_value_t result = eval_str(script, sz);
    if(jerry_value_is_error(result)) {
      fprintf(stderr, "Failed to evaluate shim.min.js");
      res = 1;
      goto cleanup;
    }

    jerry_value_free(result);
  }

  /* evaluate xlsx.full.min.js */
  {
    size_t sz; const jerry_char_t *script = read_file("xlsx.full.min.js", &sz);
    jerry_value_t result = eval_str(script, sz);
    if(jerry_value_is_error(result)) {
      fprintf(stderr, "Failed to evaluate xlsx.full.min.js");
      res = 2;
      goto cleanup;
    }

    jerry_value_free(result);
  }

  /* load spreadsheet */
  jerry_value_t ab = load_file(argv[1]);
  if(!ab || jerry_value_is_error(ab)) {
    fprintf(stderr, "Failed to read %s", argv[1]);
    res = 3;
    goto exeunt;
  }

  /* assign to `buf` in the global scope */
  {
    /* get `this` */
    jerry_value_t this = jerry_current_realm();
    if(jerry_value_is_error(this)) {
      fprintf(stderr, "Failed to get global object");
      res = 4;
      goto exeunt;
    }

    /* create "buf" str */
    jerry_value_t prop = jerry_string_sz("buf");
    if(jerry_value_is_error(this)) {
      fprintf(stderr, "Failed to create string");
      res = 5;
      goto exeunt;
    }

    /* equivalent of `this["buf"] = buf` */
    jerry_value_t set = jerry_object_set(this, prop, ab);
    if(jerry_value_is_error(set)) {
      fprintf(stderr, "Failed to assign ArrayBuffer");
      res = 6;
      goto exeunt;
    }
  }

  /* run `var wb = XLSX.read(buf)` */
  {
    const jerry_char_t code[] = "var wb = XLSX.read(buf);";
    jerry_value_t result = eval_str(code, sizeof(code) - 1);
    if(jerry_value_is_error(result)) {
      fprintf(stderr, "Failed to parse file");
      res = 7;
      goto exeunt;
    }
    jerry_value_free(result);
  }

  /* run `XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]])` and print result */
  {
    const jerry_char_t code[] = "XLSX.utils.sheet_to_csv(wb.Sheets[wb.SheetNames[0]])";
    jerry_value_t result = eval_str(code, sizeof(code) - 1);
    if(jerry_value_is_error(result)) {
      fprintf(stderr, "Failed to generate csv");
      res = 8;
    } else {
      size_t sz; char *buf = pull_str(result, &sz);
      printf("%s\n", buf);
    }
    jerry_value_free(result);
  }

exeunt:
  jerry_value_free(ab);

cleanup:
  /* Cleanup engine */
  jerry_cleanup();
  return res;
}
