// This is a generated file, modify: generate/templates/templates/class_content.cc

#include <nan.h>
#include <string.h>

extern "C" {
#include <git2.h>
}

#include "../include/nodegit.h"
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/config.h"
#include "nodegit_wrapper.cc"
#include "../include/async_libgit2_queue_worker.h"

#include "../include/git_buf_converter.h"
#include "../include/buf.h"
#include "../include/transaction.h"

#include <iostream>

using namespace std;
using namespace v8;
using namespace node;

GitConfig::~GitConfig()
{
  // this will cause an error if you have a non-self-freeing object that also needs
  // to save values. Since the object that will eventually free the object has no
  // way of knowing to free these values.
}

void GitConfig::InitializeComponent(v8::Local<v8::Object> target)
{
  Nan::HandleScope scope;

  v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);

  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(Nan::New("Config").ToLocalChecked());

  Nan::SetMethod(tpl, "findProgramdata", FindProgramdata);
  Nan::SetPrototypeMethod(tpl, "getStringBuf", GetStringBuf);
  Nan::SetPrototypeMethod(tpl, "lock", Lock);
  Nan::SetMethod(tpl, "openDefault", OpenDefault);
  Nan::SetPrototypeMethod(tpl, "setInt64", SetInt64);
  Nan::SetPrototypeMethod(tpl, "setMultivar", SetMultivar);
  Nan::SetPrototypeMethod(tpl, "setString", SetString);
  Nan::SetPrototypeMethod(tpl, "snapshot", Snapshot);

  InitializeTemplate(tpl);

  v8::Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
  constructor_template.Reset(_constructor_template);
  Nan::Set(target, Nan::New("Config").ToLocalChecked(), _constructor_template);
}


/*
   * @param Buf callback
   */
NAN_METHOD(GitConfig::FindProgramdata)
{

  if (info.Length() == 0 || !info[0]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  FindProgramdataBaton* baton = new FindProgramdataBaton;

  baton->error_code = GIT_OK;
  baton->error = NULL;

  baton->out = (git_buf *)malloc(sizeof(git_buf ));;
  baton->out->ptr = NULL;
  baton->out->size = baton->out->asize = 0;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[0]));
  FindProgramdataWorker *worker = new FindProgramdataWorker(baton, callback);

  AsyncLibgit2QueueWorker(worker);
  return;
}

void GitConfig::FindProgramdataWorker::Execute()
{
  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */true,baton->out
                         );

    int result = git_config_find_programdata(
                   baton->out    );

    baton->error_code = result;

    if (result != GIT_OK && giterr_last() != NULL) {
      baton->error = git_error_dup(giterr_last());
    }

  }
}

void GitConfig::FindProgramdataWorker::HandleOKCallback()
{
  if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> to;
// start convert_to_v8 block
    if (baton->out) {
      to = Nan::New<String>(baton->out->ptr, baton->out->size).ToLocalChecked();
    } else {
      to = Nan::Null();
    }
// end convert_to_v8 block
    v8::Local<v8::Value> result = to;
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::Error(baton->error->message)->ToObject();
      } else {
        err = Nan::Error("Method findProgramdata has thrown an error.")->ToObject();
      }
      err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      std::queue< v8::Local<v8::Value> > workerArguments;
      bool callbackFired = false;
      while(!workerArguments.empty()) {
        v8::Local<v8::Value> node = workerArguments.front();
        workerArguments.pop();

        if (
          !node->IsObject()
          || node->IsArray()
          || node->IsBooleanObject()
          || node->IsDate()
          || node->IsFunction()
          || node->IsNumberObject()
          || node->IsRegExp()
          || node->IsStringObject()
        ) {
          continue;
        }

        v8::Local<v8::Object> nodeObj = node->ToObject();
        v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());

        if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            checkValue->ToObject()
          };
          callback->Call(1, argv);
          callbackFired = true;
          break;
        }

        v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
        for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
          v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
          v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
          if (!nodeToQueue->IsUndefined()) {
            workerArguments.push(nodeToQueue);
          }
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::Error("Method findProgramdata has thrown an error.")->ToObject();
        err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv);
      }
    } else {
      callback->Call(0, NULL);
    }

  }

  git_buf_free(baton->out);
  free((void *)baton->out);

  delete baton;
}


/*
    * @param String name
    * @param Buf callback
   */
NAN_METHOD(GitConfig::GetStringBuf)
{

  if (info.Length() == 0 || !info[0]->IsString()) {
    return Nan::ThrowError("String name is required.");
  }

  if (info.Length() == 1 || !info[1]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  GetStringBufBaton* baton = new GetStringBufBaton;

  baton->error_code = GIT_OK;
  baton->error = NULL;

  baton->out = (git_buf *)malloc(sizeof(git_buf ));;
  baton->out->ptr = NULL;
  baton->out->size = baton->out->asize = 0;
  baton->cfg = Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue();
// start convert_from_v8 block
  const char * from_name = NULL;

  String::Utf8Value name(info[0]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_name = (const char *) malloc(name.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_name, *name, name.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_name) + name.length()), 0, 1);
// end convert_from_v8 block
  baton->name = from_name;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[1]));
  GetStringBufWorker *worker = new GetStringBufWorker(baton, callback);
  worker->SaveToPersistent("cfg", info.This());
  if (!info[0]->IsUndefined() && !info[0]->IsNull())
    worker->SaveToPersistent("name", info[0]->ToObject());

  AsyncLibgit2QueueWorker(worker);
  return;
}

void GitConfig::GetStringBufWorker::Execute()
{
  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */true,baton->out
                                           ,baton->cfg
                                           ,baton->name
                         );

    int result = git_config_get_string_buf(
                   baton->out,baton->cfg,baton->name    );

    baton->error_code = result;

    if (result != GIT_OK && giterr_last() != NULL) {
      baton->error = git_error_dup(giterr_last());
    }

  }
}

void GitConfig::GetStringBufWorker::HandleOKCallback()
{
  if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> to;
// start convert_to_v8 block
    if (baton->out) {
      to = Nan::New<String>(baton->out->ptr, baton->out->size).ToLocalChecked();
    } else {
      to = Nan::Null();
    }
// end convert_to_v8 block
    v8::Local<v8::Value> result = to;
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::Error(baton->error->message)->ToObject();
      } else {
        err = Nan::Error("Method getStringBuf has thrown an error.")->ToObject();
      }
      err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      std::queue< v8::Local<v8::Value> > workerArguments;
      workerArguments.push(GetFromPersistent("name"));
      bool callbackFired = false;
      while(!workerArguments.empty()) {
        v8::Local<v8::Value> node = workerArguments.front();
        workerArguments.pop();

        if (
          !node->IsObject()
          || node->IsArray()
          || node->IsBooleanObject()
          || node->IsDate()
          || node->IsFunction()
          || node->IsNumberObject()
          || node->IsRegExp()
          || node->IsStringObject()
        ) {
          continue;
        }

        v8::Local<v8::Object> nodeObj = node->ToObject();
        v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());

        if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            checkValue->ToObject()
          };
          callback->Call(1, argv);
          callbackFired = true;
          break;
        }

        v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
        for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
          v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
          v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
          if (!nodeToQueue->IsUndefined()) {
            workerArguments.push(nodeToQueue);
          }
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::Error("Method getStringBuf has thrown an error.")->ToObject();
        err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv);
      }
    } else {
      callback->Call(0, NULL);
    }

  }

  git_buf_free(baton->out);
  free((void *)baton->out);

  delete baton;
}


/*
 * @param Transaction tx
       * @return Number  result    */
NAN_METHOD(GitConfig::Lock)
{
  Nan::EscapableHandleScope scope;

  if (info.Length() == 0 || !info[0]->IsObject()) {
    return Nan::ThrowError("Transaction tx is required.");
  }

// start convert_from_v8 block
  git_transaction ** from_tx = NULL;
  *from_tx = Nan::ObjectWrap::Unwrap<GitTransaction>(info[0]->ToObject())->GetValue();
// end convert_from_v8 block

  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */false,    from_tx
                                           ,    Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                         );

    int result = git_config_lock(
                   from_tx
                   ,  Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                 );


    v8::Local<v8::Value> to;
// start convert_to_v8 block
    to = Nan::New<Number>( result);
    // end convert_to_v8 block
    return info.GetReturnValue().Set(scope.Escape(to));
  }
}

/*
   * @param Config callback
   */
NAN_METHOD(GitConfig::OpenDefault)
{

  if (info.Length() == 0 || !info[0]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  OpenDefaultBaton* baton = new OpenDefaultBaton;

  baton->error_code = GIT_OK;
  baton->error = NULL;


  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[0]));
  OpenDefaultWorker *worker = new OpenDefaultWorker(baton, callback);

  AsyncLibgit2QueueWorker(worker);
  return;
}

void GitConfig::OpenDefaultWorker::Execute()
{
  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */true);

    int result = git_config_open_default(
                   &baton->out    );

    baton->error_code = result;

    if (result != GIT_OK && giterr_last() != NULL) {
      baton->error = git_error_dup(giterr_last());
    }

  }
}

void GitConfig::OpenDefaultWorker::HandleOKCallback()
{
  if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> to;
// start convert_to_v8 block

    if (baton->out != NULL) {
      // GitConfig baton->out
      to = GitConfig::New(baton->out, false  );
    } else {
      to = Nan::Null();
    }

// end convert_to_v8 block
    v8::Local<v8::Value> result = to;
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::Error(baton->error->message)->ToObject();
      } else {
        err = Nan::Error("Method openDefault has thrown an error.")->ToObject();
      }
      err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      std::queue< v8::Local<v8::Value> > workerArguments;
      bool callbackFired = false;
      while(!workerArguments.empty()) {
        v8::Local<v8::Value> node = workerArguments.front();
        workerArguments.pop();

        if (
          !node->IsObject()
          || node->IsArray()
          || node->IsBooleanObject()
          || node->IsDate()
          || node->IsFunction()
          || node->IsNumberObject()
          || node->IsRegExp()
          || node->IsStringObject()
        ) {
          continue;
        }

        v8::Local<v8::Object> nodeObj = node->ToObject();
        v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());

        if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            checkValue->ToObject()
          };
          callback->Call(1, argv);
          callbackFired = true;
          break;
        }

        v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
        for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
          v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
          v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
          if (!nodeToQueue->IsUndefined()) {
            workerArguments.push(nodeToQueue);
          }
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::Error("Method openDefault has thrown an error.")->ToObject();
        err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv);
      }
    } else {
      callback->Call(0, NULL);
    }

  }


  delete baton;
}


/*
   * @param String name
   * @param Number value
     * @return Number  result    */
NAN_METHOD(GitConfig::SetInt64)
{
  Nan::EscapableHandleScope scope;

  if (info.Length() == 0 || !info[0]->IsString()) {
    return Nan::ThrowError("String name is required.");
  }

  if (info.Length() == 1 || !info[1]->IsNumber()) {
    return Nan::ThrowError("Number value is required.");
  }

// start convert_from_v8 block
  const char * from_name = NULL;

  String::Utf8Value name(info[0]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_name = (const char *) malloc(name.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_name, *name, name.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_name) + name.length()), 0, 1);
// end convert_from_v8 block
// start convert_from_v8 block
  int64_t from_value;
  from_value = (int64_t)   info[1]->ToNumber()->Value();
// end convert_from_v8 block

  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */false,    Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                                           ,    from_name
                         );

    int result = git_config_set_int64(
                   Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                   ,  from_name
                   ,  from_value
                 );


    v8::Local<v8::Value> to;
// start convert_to_v8 block
    to = Nan::New<Number>( result);
    // end convert_to_v8 block
    return info.GetReturnValue().Set(scope.Escape(to));
  }
}

/*
   * @param String name
   * @param String regexp
   * @param String value
     * @return Number  result    */
NAN_METHOD(GitConfig::SetMultivar)
{
  Nan::EscapableHandleScope scope;

  if (info.Length() == 0 || !info[0]->IsString()) {
    return Nan::ThrowError("String name is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String regexp is required.");
  }

  if (info.Length() == 2 || !info[2]->IsString()) {
    return Nan::ThrowError("String value is required.");
  }

// start convert_from_v8 block
  const char * from_name = NULL;

  String::Utf8Value name(info[0]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_name = (const char *) malloc(name.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_name, *name, name.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_name) + name.length()), 0, 1);
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_regexp = NULL;

  String::Utf8Value regexp(info[1]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_regexp = (const char *) malloc(regexp.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_regexp, *regexp, regexp.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_regexp) + regexp.length()), 0, 1);
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_value = NULL;

  String::Utf8Value value(info[2]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_value = (const char *) malloc(value.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_value, *value, value.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_value) + value.length()), 0, 1);
// end convert_from_v8 block

  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */false,    Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                                           ,    from_name
                                           ,    from_regexp
                                           ,    from_value
                         );

    int result = git_config_set_multivar(
                   Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue()
                   ,  from_name
                   ,  from_regexp
                   ,  from_value
                 );


    v8::Local<v8::Value> to;
// start convert_to_v8 block
    to = Nan::New<Number>( result);
    // end convert_to_v8 block
    return info.GetReturnValue().Set(scope.Escape(to));
  }
}

/*
   * @param String name
   * @param String value
     */
NAN_METHOD(GitConfig::SetString)
{

  if (info.Length() == 0 || !info[0]->IsString()) {
    return Nan::ThrowError("String name is required.");
  }

  if (info.Length() == 1 || !info[1]->IsString()) {
    return Nan::ThrowError("String value is required.");
  }

  if (info.Length() == 2 || !info[2]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  SetStringBaton* baton = new SetStringBaton;

  baton->error_code = GIT_OK;
  baton->error = NULL;

  baton->cfg = Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue();
// start convert_from_v8 block
  const char * from_name = NULL;

  String::Utf8Value name(info[0]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_name = (const char *) malloc(name.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_name, *name, name.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_name) + name.length()), 0, 1);
// end convert_from_v8 block
  baton->name = from_name;
// start convert_from_v8 block
  const char * from_value = NULL;

  String::Utf8Value value(info[1]->ToString());
  // malloc with one extra byte so we can add the terminating null character C-strings expect:
  from_value = (const char *) malloc(value.length() + 1);
  // copy the characters from the nodejs string into our C-string (used instead of strdup or strcpy because nulls in
  // the middle of strings are valid coming from nodejs):
  memcpy((void *)from_value, *value, value.length());
  // ensure the final byte of our new string is null, extra casts added to ensure compatibility with various C types
  // used in the nodejs binding generation:
  memset((void *)(((char *)from_value) + value.length()), 0, 1);
// end convert_from_v8 block
  baton->value = from_value;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[2]));
  SetStringWorker *worker = new SetStringWorker(baton, callback);
  worker->SaveToPersistent("cfg", info.This());
  if (!info[0]->IsUndefined() && !info[0]->IsNull())
    worker->SaveToPersistent("name", info[0]->ToObject());
  if (!info[1]->IsUndefined() && !info[1]->IsNull())
    worker->SaveToPersistent("value", info[1]->ToObject());

  AsyncLibgit2QueueWorker(worker);
  return;
}

void GitConfig::SetStringWorker::Execute()
{
  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */true,baton->cfg
                                           ,baton->name
                                           ,baton->value
                         );

    int result = git_config_set_string(
                   baton->cfg,baton->name,baton->value    );

    baton->error_code = result;

    if (result != GIT_OK && giterr_last() != NULL) {
      baton->error = git_error_dup(giterr_last());
    }

  }
}

void GitConfig::SetStringWorker::HandleOKCallback()
{
  if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> result = Nan::Undefined();
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::Error(baton->error->message)->ToObject();
      } else {
        err = Nan::Error("Method setString has thrown an error.")->ToObject();
      }
      err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      std::queue< v8::Local<v8::Value> > workerArguments;
      workerArguments.push(GetFromPersistent("name"));
      workerArguments.push(GetFromPersistent("value"));
      bool callbackFired = false;
      while(!workerArguments.empty()) {
        v8::Local<v8::Value> node = workerArguments.front();
        workerArguments.pop();

        if (
          !node->IsObject()
          || node->IsArray()
          || node->IsBooleanObject()
          || node->IsDate()
          || node->IsFunction()
          || node->IsNumberObject()
          || node->IsRegExp()
          || node->IsStringObject()
        ) {
          continue;
        }

        v8::Local<v8::Object> nodeObj = node->ToObject();
        v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());

        if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            checkValue->ToObject()
          };
          callback->Call(1, argv);
          callbackFired = true;
          break;
        }

        v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
        for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
          v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
          v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
          if (!nodeToQueue->IsUndefined()) {
            workerArguments.push(nodeToQueue);
          }
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::Error("Method setString has thrown an error.")->ToObject();
        err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv);
      }
    } else {
      callback->Call(0, NULL);
    }

  }


  delete baton;
}


/*
     * @param Config callback
   */
NAN_METHOD(GitConfig::Snapshot)
{

  if (info.Length() == 0 || !info[0]->IsFunction()) {
    return Nan::ThrowError("Callback is required and must be a Function.");
  }

  SnapshotBaton* baton = new SnapshotBaton;

  baton->error_code = GIT_OK;
  baton->error = NULL;

  baton->config = Nan::ObjectWrap::Unwrap<GitConfig>(info.This())->GetValue();

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[0]));
  SnapshotWorker *worker = new SnapshotWorker(baton, callback);
  worker->SaveToPersistent("config", info.This());

  AsyncLibgit2QueueWorker(worker);
  return;
}

void GitConfig::SnapshotWorker::Execute()
{
  giterr_clear();

  {
    LockMaster lockMaster(/*asyncAction: */true,baton->config
                         );

    int result = git_config_snapshot(
                   &baton->out,baton->config    );

    baton->error_code = result;

    if (result != GIT_OK && giterr_last() != NULL) {
      baton->error = git_error_dup(giterr_last());
    }

  }
}

void GitConfig::SnapshotWorker::HandleOKCallback()
{
  if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> to;
// start convert_to_v8 block

    if (baton->out != NULL) {
      // GitConfig baton->out
      to = GitConfig::New(baton->out, false  );
    } else {
      to = Nan::Null();
    }

// end convert_to_v8 block
    v8::Local<v8::Value> result = to;
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::Error(baton->error->message)->ToObject();
      } else {
        err = Nan::Error("Method snapshot has thrown an error.")->ToObject();
      }
      err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      std::queue< v8::Local<v8::Value> > workerArguments;
      bool callbackFired = false;
      while(!workerArguments.empty()) {
        v8::Local<v8::Value> node = workerArguments.front();
        workerArguments.pop();

        if (
          !node->IsObject()
          || node->IsArray()
          || node->IsBooleanObject()
          || node->IsDate()
          || node->IsFunction()
          || node->IsNumberObject()
          || node->IsRegExp()
          || node->IsStringObject()
        ) {
          continue;
        }

        v8::Local<v8::Object> nodeObj = node->ToObject();
        v8::Local<v8::Value> checkValue = GetPrivate(nodeObj, Nan::New("NodeGitPromiseError").ToLocalChecked());

        if (!checkValue.IsEmpty() && !checkValue->IsNull() && !checkValue->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            checkValue->ToObject()
          };
          callback->Call(1, argv);
          callbackFired = true;
          break;
        }

        v8::Local<v8::Array> properties = nodeObj->GetPropertyNames();
        for (unsigned int propIndex = 0; propIndex < properties->Length(); ++propIndex) {
          v8::Local<v8::String> propName = properties->Get(propIndex)->ToString();
          v8::Local<v8::Value> nodeToQueue = nodeObj->Get(propName);
          if (!nodeToQueue->IsUndefined()) {
            workerArguments.push(nodeToQueue);
          }
        }
      }

      if (!callbackFired) {
        v8::Local<v8::Object> err = Nan::Error("Method snapshot has thrown an error.")->ToObject();
        err->Set(Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
        v8::Local<v8::Value> argv[1] = {
          err
        };
        callback->Call(1, argv);
      }
    } else {
      callback->Call(0, NULL);
    }

  }


  delete baton;
}

// force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<GitConfigTraits>;
