#include "transaction.h"
#include "table.h"
#include "timer.h"

using namespace v8;

#define UNWRAP() Nan::ObjectWrap::Unwrap<Transaction>(info.Holder())
#define CHECK_FINISHED(obj) if (obj->ref == NULL) { \
  return Nan::ThrowReferenceError("Transaction is finished"); \
}

Nan::Persistent<Function> Transaction::constructor;

Transaction::Transaction(libagent_Transaction *ref, Libagent *libagent) : ref(ref), libagent(libagent) {}

Transaction::~Transaction() {
  if (ref) {
    libagent->finish_transaction(ref);
    ref = NULL;
  }
};

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

  v8::Local<v8::ObjectTemplate> instance = ctor->InstanceTemplate();
  instance->SetInternalFieldCount(1);
  
  Nan::SetPrototypeMethod(ctor, "createArray", CreateArray);
  Nan::SetPrototypeMethod(ctor, "createMap", CreateMap);
  Nan::SetPrototypeMethod(ctor, "runHook", RunHook);
  Nan::SetPrototypeMethod(ctor, "hasHook", HasHook);
  Nan::SetPrototypeMethod(ctor, "hookRan", HookRan);
  Nan::SetPrototypeMethod(ctor, "finish", Finish);
  Nan::SetPrototypeMethod(ctor, "startTimer", StartTimer);
  Nan::SetAccessor(instance, Nan::New("uuid").ToLocalChecked(), Uuid);

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

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

Local<Value> Transaction::Start(Agent *agent, const char *uuid) {
  libagent_Transaction *ref = agent->libagent->start_transaction(agent->ref, uuid);
  if (ref == NULL) {
    return Nan::Null();
  }

  Local<Function> ctor = Nan::New(Transaction::constructor);
  Local<Object> val = Nan::NewInstance(ctor).ToLocalChecked();
  Transaction *obj = new Transaction(ref, agent->libagent);
  obj->Wrap(val);

  return val;
}

NAN_GETTER(Transaction::Uuid) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  const char *uuid = obj->libagent->transaction_uuid(obj->ref);
  Local<Value> val = Nan::Encode(uuid, strlen(uuid));
  obj->libagent->drop_string(uuid);
  info.GetReturnValue().Set(val);
}

NAN_METHOD(Transaction::CreateArray) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  int size = 0;

  if (info.Length() > 1) {
    if (!info[0]->IsNumber()) {
      return Nan::ThrowTypeError("Integer argument required");
    }
    size = Nan::To<int>(info[0]).FromJust();
  }

  info.GetReturnValue().Set(Table::CreateArray(obj, size)->ToValue());
}

NAN_METHOD(Transaction::CreateMap) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  int size = 0;

  if (info.Length() > 1) {
    if (!info[0]->IsNumber()) {
      return Nan::ThrowTypeError("Integer argument required");
    }
    size = Nan::To<int>(info[0]).FromJust();
  }

  info.GetReturnValue().Set(Table::CreateMap(obj, size)->ToValue());
}

NAN_METHOD(Transaction::RunHook) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  if (info.Length() < 2) {
    return Nan::ThrowTypeError("runHook requires at least 2 arguments");
  }

  if (!info[0]->IsString() || !info[1]->IsString()) {
    return Nan::ThrowTypeError("First and second arguments must be strings");
  }

  Nan::Utf8String plugin(info[0]);
  Nan::Utf8String hook(info[1]);

  Table *meta = NULL;
  if (info.Length() > 2) {
    if (info[2]->IsNull() || info[2]->IsUndefined()) {
      // meta stay NULL
    } else if (info[2]->IsObject()) {
      meta = Table::FromObject(obj, Nan::To<Object>(info[2]).ToLocalChecked());
    } else {
      return Nan::ThrowTypeError("Third argument must be an object");
    }
  }

  libagent_Table *ref = obj->libagent->run_hook(obj->ref, *plugin, *hook,
                                        meta ? meta->ref : NULL);
  if (ref) {
    Table *table = new Table(obj, ref);
    info.GetReturnValue().Set(table->ToValue());
  } else {
    info.GetReturnValue().SetNull();
  }
}

NAN_METHOD(Transaction::HasHook) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  if (info.Length() < 1 || !info[0]->IsString()) {
    return Nan::ThrowTypeError("hasHook requires one string argument");
  }

  Nan::Utf8String hook(info[0]);

  bool ran = obj->libagent->has_hook(obj->ref, *hook);
  info.GetReturnValue().Set(ran);
}

NAN_METHOD(Transaction::HookRan) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  if (info.Length() < 1 || !info[0]->IsString()) {
    return Nan::ThrowTypeError("hookRan requires one string argument");
  }

  Nan::Utf8String hook(info[0]);

  bool ran = obj->libagent->hook_ran(obj->ref, *hook);
  info.GetReturnValue().Set(ran);
}

NAN_METHOD(Transaction::Finish) {
  Transaction* obj = UNWRAP();
  CHECK_FINISHED(obj);

  if (obj->ref) {
    obj->libagent->finish_transaction(obj->ref);
    obj->ref = NULL;
  }
}

NAN_METHOD(Transaction::StartTimer) {
  Transaction* obj = UNWRAP();

  if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsString()) {
    return Nan::ThrowTypeError("startTimer requires two string arguments");
  }

  Nan::Utf8String kind(info[0]);
  Nan::Utf8String name(info[1]);

  info.GetReturnValue().Set(Timer::Start(obj, *kind, *name));
}
