#define TABULA_ENTRY_POINT 1

#include <tabula.h>

#include <struo/struo.h>

#define cli_warning(FORMAT, ...) \
	do { \
		fprintf(stderr, "%s:%i: warning: " FORMAT, __FILE__, __LINE__, ## __VA_ARGS__); \
	} while(0)

static struct struo_Options global_options;

static void data_file_read_error(void *ud) {
}

static void data_file_read_partial(void *ud, const void *data, uint64_t length) {
  printf("%.*s", (int)(length), (const char *)data);
}

static void data_file_read_done(void *ud) {
}

bool alias_libuv_entry_point(int argc, char * argv []);

int tabula_entry_point(int argc, char * argv []) {
  argv = uv_setup_args(argc, argv);
  alias_libuv_init();
  if(alias_libuv_entry_point(argc, argv)) {
    alias_libuv_run_forever();
  }
  return 0;
}

static void data_paths_find_error(void *ud) {
  // TODO
}

static void data_paths_find_found(void *ud, alias_str path) {
  printf("%s\n", path);

  alias_DirectoryList_read(&global_options.data_paths, path, data_file_read_error, data_file_read_partial, data_file_read_done, NULL);
}

static void data_paths_find_done_show_files(void *ud) {
}

bool alias_libuv_entry_point(int argc, char * argv []) {

  struo_Options_init(&global_options);

  bool build_path_defined = false;
  bool output_path_defined = false;

  for(int i = 1; i < argc; ) {
    const char * arg = argv[i++];

    if(!strcmp(arg, "--asset-path")) {
      struo_Options_add_asset_path(&global_options, argv[i++]);
    } else if(!strcmp(arg, "--data-path")) {
      struo_Options_add_data_path(&global_options, argv[i++]);
    } else if(!strcmp(arg, "--build-path")) {
      if(build_path_defined) {
        cli_warning("build path already defined, ignoring extra parameter");
        i++;
      } else {
        struo_Options_set_build_path(&global_options, argv[i++]);
        build_path_defined = true;
      }
    } else if(!strcmp(arg, "--output-path")) {
      if(output_path_defined) {
        cli_warning("output path already defined, ignoring extra parameter");
        i++;
      } else {
        struo_Options_set_output_path(&global_options, argv[i++]);
        output_path_defined = true;
      }    
    }
  }

  alias_DirectoryList_find(&global_options.data_paths, "*.txt", data_paths_find_error, data_paths_find_found, data_paths_find_done_show_files, NULL);

  return true;
}