#include "nodeagent.h"
#include "transaction.h"

using namespace v8;

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

Agent::Agent(libagent_Agent *ref, Libagent *libagent) : ref(ref), libagent(libagent) {
  assert(ref);
};

Agent::~Agent() {
  libagent->close_agent(ref);
  ref = NULL;
};

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

  v8::Local<v8::ObjectTemplate> instance = ctor->InstanceTemplate();
  instance->SetInternalFieldCount(1);
  
  Nan::SetPrototypeMethod(ctor, "startTransaction", StartTransaction);
  Nan::SetAccessor(instance, Nan::New("enabled").ToLocalChecked(), Enabled);
  Nan::SetPrototypeMethod(ctor, "log", Log);
  Nan::SetPrototypeMethod(ctor, "isLogEnabled", IsLogEnabled);
  Nan::SetPrototypeMethod(ctor, "isPluginEnabled", IsPluginEnabled);
  Nan::SetPrototypeMethod(ctor, "report", Report);
  Nan::SetPrototypeMethod(ctor, "reportPlugin", ReportPlugin);

  Nan::Set(target, Nan::New("Agent").ToLocalChecked(), Nan::GetFunction(ctor).ToLocalChecked());
}

NAN_METHOD(Agent::New) {
  if (!info.IsConstructCall()) {
    return Nan::ThrowTypeError("Use new to create an instance");
  }

  if (info.Length() < 1 || !info[0]->IsString()) {
    return Nan::ThrowTypeError("version string required as the first argument");
  }
  if (info.Length() < 2 || !info[1]->IsString()) {
    return Nan::ThrowTypeError("base path required as the second argument");
  }

  Nan::Utf8String version(info[0]);
  Nan::Utf8String base(info[1]);

  Libagent *libagent = Libagent::load(*base);
  if (libagent == NULL)
    return Nan::ThrowError("failed to load libagent");

  libagent_Config *config = libagent->new_config();

  if (info.Length() > 2 && info[2]->IsObject()) {
    Local<Object> fields = Nan::To<Object>(info[2]).ToLocalChecked();
    Local<Array> keys = Nan::GetOwnPropertyNames(fields).ToLocalChecked();

    for (uint32_t i = 0; i < keys->Length(); i++) {
      Local<Value> key = Nan::Get(keys, i).ToLocalChecked();
      Nan::Utf8String skey(key);
      Nan::Utf8String val(Nan::Get(fields, key).ToLocalChecked());
      libagent->set_config(config, *skey, *val);
    }
  }

  Agent* obj = new Agent(libagent->new_agent("agent-node", *version, config), libagent);
  obj->Wrap(info.This());
}

NAN_GETTER(Agent::Enabled) {
  Agent* obj = UNWRAP();
  info.GetReturnValue().Set((bool) obj->libagent->is_enabled(obj->ref));
}

NAN_METHOD(Agent::StartTransaction) {
  Agent* obj = UNWRAP();
  Nan::Utf8String uuid(info[0]);
  Local<Value> transaction;

  if (info.Length() > 0) {
    if (!info[0]->IsString()) {
      return Nan::ThrowTypeError("startTransaction first argument must be a string");
    }
    transaction = Transaction::Start(obj, *uuid);
  } else {
    transaction = Transaction::Start(obj, NULL);
  }

  info.GetReturnValue().Set(transaction);
}

NAN_METHOD(Agent::Log) {
  Agent* obj = UNWRAP();

  if (info.Length() != 3) {
    return Nan::ThrowTypeError("log requires 3 arguments");
  }

  if (!info[0]->IsString() || !info[1]->IsNumber() || !info[2]->IsString()) {
    return Nan::ThrowTypeError("log requires string, int, string");
  }

  Nan::Utf8String target(info[0]);
  int level = Nan::To<int>(info[1]).FromJust();
  Nan::Utf8String message(info[2]);

  obj->libagent->log(obj->ref, *target, NULL, 0, level, *message);
}

NAN_METHOD(Agent::IsLogEnabled) {
  Agent* obj = UNWRAP();
  if (info.Length() != 1 || !info[0]->IsNumber()) {
    return Nan::ThrowTypeError("isLogEnabled requires one integer argument");
  }

  int level = Nan::To<int>(info[0]).FromJust();

  info.GetReturnValue().Set((bool) obj->libagent->is_log_enabled(obj->ref, level));
}

NAN_METHOD(Agent::IsPluginEnabled) {
  Agent* obj = UNWRAP();
  if (info.Length() != 1 || !info[0]->IsString()) {
    return Nan::ThrowTypeError("isPluginEnabled requires one string argument");
  }

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

  info.GetReturnValue().Set((bool) obj->libagent->is_plugin_enabled(obj->ref, *plugin));
}

NAN_METHOD(Agent::Report) {
  Agent* obj = UNWRAP();

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

  if (!info[0]->IsString() || !info[1]->IsString()) {
    return Nan::ThrowTypeError("report requires at least two string arguments");
  }

  Nan::Utf8String type(info[0]);
  Nan::Utf8String name(info[1]);
  Nan::Utf8String version(info[2]);

  obj->libagent->report(obj->ref, *type, *name, *version);
}

NAN_METHOD(Agent::ReportPlugin) {
  Agent* obj = UNWRAP();

  Nan::Utf8String name(info[0]);
  Nan::Utf8String hooks(info[1]);
  Nan::Utf8String status(info[2]);
  Nan::Utf8String version(info[3]);

  obj->libagent->report_plugin(obj->ref,
    *name,
    info[1]->IsString() ? *hooks : NULL,
    info[2]->IsString() ? *status : NULL,
    info[3]->IsString() ? *version : NULL
  );
}
