#pragma once

#include <stdbool.h>

#include "quickjs.h"

struct uv_loop_s;
typedef struct uv_loop_s uv_loop_t;
typedef struct uv_timer_s uv_timer_t;

typedef int taskid_t;
typedef int promiseid_t;
typedef int exportid_t;
typedef struct _tf_taskstub_t tf_taskstub_t;
typedef struct _tf_task_t tf_task_t;
typedef struct _tf_trace_t tf_trace_t;
typedef struct _tf_ssb_t tf_ssb_t;

static const taskid_t k_task_parent_id = 0;

typedef enum _tf_task_message_t {
	kResolvePromise,
	kRejectPromise,
	kInvokeExport,
	kReleaseExport,
	kReleaseImport,
	kActivate,
	kExecute,
	kKill,
	kSetImports,
	kGetExports,
	kLoadFile,
	kTaskError,
	kTaskTrace,
	kPrint,
} tf_task_message_t;

tf_task_t* tf_task_create();
void tf_task_configure_from_stdin(tf_task_t* task);
void tf_task_set_ssb_port(tf_task_t* task, int port);
void tf_task_set_http_port(tf_task_t* task, int port);
void tf_task_set_https_port(tf_task_t* task, int port);
void tf_task_set_db_path(tf_task_t* task, const char* path);
void tf_task_set_zip_path(tf_task_t* task, const char* path);
const char* tf_task_get_zip_path(tf_task_t* task);
void tf_task_set_args(tf_task_t* task, const char* args);
void tf_task_activate(tf_task_t* task);
void tf_task_run(tf_task_t* task);
int tf_task_execute(tf_task_t* task, const char* file);
void tf_task_set_trusted(tf_task_t* task, bool trusted);
JSContext* tf_task_get_context(tf_task_t* task);
void tf_task_destroy(tf_task_t* task);
exportid_t tf_task_export_function(tf_task_t* task, tf_taskstub_t* to, JSValue function);
JSValue tf_task_add_import(tf_task_t* task, taskid_t stub_id, exportid_t export_id);
uv_loop_t* tf_task_get_loop(tf_task_t* task);
tf_task_t* tf_task_get(JSContext* context);
tf_trace_t* tf_task_get_trace(tf_task_t* task);
tf_ssb_t* tf_task_get_ssb(tf_task_t* task);
const char* tf_task_get_name(tf_task_t* task);
void tf_task_print(tf_task_t* task, int argc, JSValueConst* argv);

JSValue tf_task_allocate_promise(tf_task_t* task, promiseid_t* out_promise);
void tf_task_reject_promise(tf_task_t* task, promiseid_t promise, JSValue error);
void tf_task_resolve_promise(tf_task_t* task, promiseid_t promise, JSValue result);
void tf_task_send_promise_message(tf_task_t* from, tf_taskstub_t* to, tf_task_message_t type, promiseid_t promise, JSValue payload);

void tf_task_on_receive_packet(int packetType, const char* begin, size_t length, void* userData);
taskid_t tf_task_allocate_task_id(tf_task_t* task, tf_taskstub_t* stub);
void tf_task_remove_child(tf_task_t* task, tf_taskstub_t* child);

void tf_task_report_error(tf_task_t* task, JSValue error);

JSValue tf_try_get_typed_array_buffer(JSContext *ctx, JSValueConst obj, size_t *pbyte_offset, size_t *pbyte_length, size_t *pbytes_per_element);
uint8_t *tf_try_get_array_buffer(JSContext *ctx, size_t *psize, JSValueConst obj);

bool tf_task_send_error_to_parent(tf_task_t* task, JSValue error);
