#include "table.h"

#define UNWRAP() Nan::ObjectWrap::Unwrap<Table>(info.Holder())

Nan::Persistent<FunctionTemplate> Table::constructor;

Table::Table(Transaction *transaction, libagent_Table *ref)
  : transaction(transaction), ref(ref), libagent(transaction->libagent)
{
  assert(ref);
}

Table::~Table() {
  libagent->drop_table(ref);
  ref = NULL;
};

NAN_MODULE_INIT(Table::Init) {
  Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>();
  ctor->SetClassName(Nan::New("Table").ToLocalChecked());
  constructor.Reset(ctor);

  Local<ObjectTemplate> instance = ctor->InstanceTemplate();
  instance->SetInternalFieldCount(1);
  
  Nan::SetPrototypeMethod(ctor, "toString", ToString);
  Nan::SetAccessor(instance, Nan::New("length").ToLocalChecked(), Length);
  Nan::SetNamedPropertyHandler(instance, GetProperty, SetProperty);
  Nan::SetIndexedPropertyHandler(instance, GetIndex, SetIndex);

  Local<Function> ctorFn = Nan::GetFunction(ctor).ToLocalChecked();

  Nan::Set(target, Nan::New("Table").ToLocalChecked(), ctorFn);
}

Table *Table::CreateMap(Transaction *transaction, size_t size) {
  libagent_Table *ref = transaction->libagent->create_map(transaction->ref, size);
  return new Table(transaction, ref);
}

Table *Table::CreateArray(Transaction *transaction, size_t size) {
  libagent_Table *ref = transaction->libagent->create_array(transaction->ref, size);
  return new Table(transaction, ref);
}

Table *Table::FromObject(Transaction *transaction, Local<Object> obj) {
  if (IsTable(obj)) {
    return Nan::ObjectWrap::Unwrap<Table>(obj);
  }

  Table *table;
  Local<Array> keys = Nan::GetOwnPropertyNames(obj).ToLocalChecked();

  if (obj->IsArray()) {
    table = CreateArray(transaction, keys->Length());
  } else {
    table = CreateMap(transaction, keys->Length());
  }

  for (uint32_t i = 0; i < keys->Length(); i++) {
    Local<Value> key = Nan::Get(keys, i).ToLocalChecked();
    Local<Value> val = Nan::Get(obj, key).ToLocalChecked();
    if (obj->IsArray()) {
      table->Set(i, val);
    } else {
      Nan::Utf8String strkey(key);
      table->Set(*strkey, val);
    }
  }

  return table;
}

Local<Value> Table::ToValue() {
  Local<Function> ctor = Nan::GetFunction(Nan::New(constructor)).ToLocalChecked();
  Local<Object> val = Nan::NewInstance(ctor).ToLocalChecked();
  this->Wrap(val);
  return val;
}

bool Table::IsTable(Local<Value> val) {
  Local<FunctionTemplate> type = Nan::New(constructor);
  return type->HasInstance(val);
}

void Table::Set(const char *key, Local<Value> value) {
  if (value->IsNull() || value->IsUndefined()) {
    libagent->set_nil(ref, key);
  } else if (value->IsString()) {
    Nan::Utf8String str(value);
    libagent->set_string(ref, key, *str, str.length());
  } else if (node::Buffer::HasInstance(value)) {
    size_t len = node::Buffer::Length(value);
    char *ptr = node::Buffer::Data(value);
    libagent->set_string(ref, key, ptr, len);
  } else if (value->IsNumber()) {
    double n = Nan::To<double>(value).FromJust();
    libagent->set_number(ref, key, n);
  } else if (value->IsBoolean()) {
    int b = (int) Nan::To<bool>(value).FromJust();
    libagent->set_boolean(ref, key, b);
  } else if (value->IsObject()) {
    Table *t = Table::FromObject(transaction, Nan::To<Object>(value).ToLocalChecked());
    libagent->set_table(ref, key, t->ref);
  } else {
    return Nan::ThrowTypeError("Unsupported type for table");
  }
}

void Table::Set(int index, Local<Value> value) {
  int lindex = index + 1;

  if (value->IsNull() || value->IsUndefined()) {
    libagent->seti_nil(ref, lindex);
  } else if (value->IsString()) {
    Nan::Utf8String str(value);
    libagent->seti_string(ref, lindex, *str, str.length());
  } else if (node::Buffer::HasInstance(value)) {
    size_t len = node::Buffer::Length(value);
    char *ptr = node::Buffer::Data(value);
    libagent->seti_string(ref, lindex, ptr, len);
  } else if (value->IsNumber()) {
    double n = Nan::To<double>(value).FromJust();
    libagent->seti_number(ref, lindex, n);
  } else if (value->IsBoolean()) {
    int b = (int) Nan::To<bool>(value).FromJust();
    libagent->seti_boolean(ref, lindex, b);
  } else if (value->IsObject()) {
    Table *t = Table::FromObject(transaction, Nan::To<Object>(value).ToLocalChecked());
    libagent->seti_table(ref, lindex, t->ref);
  } else {
    return Nan::ThrowTypeError("Unsupported type for table");
  }
}

NAN_GETTER(Table::Length) {
  Table* obj = UNWRAP();
  info.GetReturnValue().Set((uint32_t) obj->libagent->len(obj->ref));
}

static void FreeCallback(char* data, void* hint) {
  Libagent *libagent = (Libagent *)hint;
  libagent->drop_string(data);
}

NAN_PROPERTY_GETTER(Table::GetProperty) {
  // Check if the property already exists on the JS object.
  // Note: HasRealNamedProperty doesn't work here, no idea why...
  if (!Nan::GetRealNamedProperty(info.This(), property).IsEmpty()) {
    // Fallback to calling to original behavior.
    return;
  }

  Table* obj = UNWRAP();
  Nan::Utf8String key(property);

  switch(obj->libagent->get_type(obj->ref, *key)) {
    case LIBAGENT_TYPE_NIL:
      info.GetReturnValue().SetNull();
      break;
    case LIBAGENT_TYPE_BOOLEAN:
      info.GetReturnValue().Set(obj->libagent->get_boolean(obj->ref, *key));
      break;
    case LIBAGENT_TYPE_NUMBER:
      info.GetReturnValue().Set(Nan::New<Number>(obj->libagent->get_number(obj->ref, *key)));
      break;
    case LIBAGENT_TYPE_STRING: {
      size_t len = 0;
      char *str = (char *) obj->libagent->get_bytes(obj->ref, *key, &len);
      info.GetReturnValue().Set(Nan::NewBuffer(
        str,
        len,
        FreeCallback,
        obj->libagent).ToLocalChecked());
      break;
    }
    case LIBAGENT_TYPE_TABLE: {
      libagent_Table *ref = obj->libagent->get_table(obj->ref, *key);
      Table *table = new Table(obj->transaction, ref);
      info.GetReturnValue().Set(table->ToValue());
      break;
    }
    default:
      info.GetReturnValue().SetUndefined();
      break;
  }
}

NAN_PROPERTY_SETTER(Table::SetProperty) {
  Table* obj = UNWRAP();
  Nan::Utf8String key(property);
  obj->Set(*key, value);
}

NAN_INDEX_GETTER(Table::GetIndex) {
  Table* obj = UNWRAP();
  int lindex = index + 1;
  
  switch(obj->libagent->geti_type(obj->ref, lindex)) {
    case LIBAGENT_TYPE_NIL:
      info.GetReturnValue().SetNull();
      break;
    case LIBAGENT_TYPE_BOOLEAN:
      info.GetReturnValue().Set(obj->libagent->geti_boolean(obj->ref, lindex));
      break;
    case LIBAGENT_TYPE_NUMBER:
      info.GetReturnValue().Set(Nan::New<Number>(obj->libagent->geti_number(obj->ref, lindex)));
      break;
    case LIBAGENT_TYPE_STRING: {
      size_t len = 0;
      char *str = (char *) obj->libagent->geti_bytes(obj->ref, lindex, &len);
      info.GetReturnValue().Set(Nan::NewBuffer(
        str,
        len,
        FreeCallback,
        obj->libagent).ToLocalChecked());
      break;
    }
    case LIBAGENT_TYPE_TABLE: {
      libagent_Table *ref = obj->libagent->geti_table(obj->ref, lindex);
      Table *table = new Table(obj->transaction, ref);
      info.GetReturnValue().Set(table->ToValue());
      break;
    }
    default:
      info.GetReturnValue().SetUndefined();
      break;
  }
}

NAN_INDEX_SETTER(Table::SetIndex) {
  Table* obj = UNWRAP();
  obj->Set(index, value);
}

NAN_METHOD(Table::ToString) {
  Table* obj = UNWRAP();
  const char *str = obj->libagent->debug(obj->ref);
  Local<Value> val = Nan::Encode(str, strlen(str));
  obj->libagent->drop_string(str);
  info.GetReturnValue().Set(val);
}
