#include "timer.h"

using namespace v8;

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

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

Timer::Timer(Transaction *transaction, libagent_Timer *ref)
  : transaction(transaction), ref(ref), libagent(transaction->libagent) {}

Timer::~Timer() {
  if (ref) {
    libagent->finish_timer(ref, transaction->ref);
    ref = NULL;
  }
};

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

  v8::Local<v8::ObjectTemplate> instance = ctor->InstanceTemplate();
  instance->SetInternalFieldCount(1);
  
  Nan::SetPrototypeMethod(ctor, "start", Start);
  Nan::SetPrototypeMethod(ctor, "stop", Stop);
  Nan::SetPrototypeMethod(ctor, "finish", Finish);

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

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

Local<Value> Timer::Start(Transaction *transaction, const char *kind, const char *name) {
  libagent_Timer *ref = transaction->libagent->new_timer(transaction->ref, kind, name);

  if (ref == NULL) {
    return Nan::Null();
  }

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

  return val;
}

NAN_METHOD(Timer::Start) {
  Timer* obj = UNWRAP();
  CHECK_FINISHED(obj);

  obj->libagent->start_timer(obj->ref);
}

NAN_METHOD(Timer::Stop) {
  Timer* obj = UNWRAP();
  CHECK_FINISHED(obj);

  obj->libagent->stop_timer(obj->ref);
}

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

  obj->libagent->finish_timer(obj->ref, obj->transaction->ref);
  obj->ref = NULL;
}
