// 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/index_conflict_iterator.h"
#include "nodegit_wrapper.cc"

  #include "../include/index.h"
  #include "../include/index_entry.h"
 
#include <iostream>

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

  GitIndexConflictIterator::~GitIndexConflictIterator() {
    // 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 GitIndexConflictIterator::InitializeComponent(v8::Local<v8::Object> target, nodegit::Context *nodegitContext) {
    Nan::HandleScope scope;

    v8::Local<v8::External> nodegitExternal = Nan::New<v8::External>(nodegitContext);
    v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction, nodegitExternal);

    tpl->InstanceTemplate()->SetInternalFieldCount(2);
    tpl->SetClassName(Nan::New("IndexConflictIterator").ToLocalChecked());

           Nan::SetMethod(tpl, "create", Create, nodegitExternal);
            Nan::SetPrototypeMethod(tpl, "next", Next, nodegitExternal);
    
    InitializeTemplate(tpl);

    v8::Local<Function> constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
    nodegitContext->SaveToPersistent("GitIndexConflictIterator::Template", constructor_template);
    Nan::Set(target, Nan::New("IndexConflictIterator").ToLocalChecked(), constructor_template);
  }

 
/*
  * @param Index index
    * @param IndexConflictIterator callback
   */
NAN_METHOD(GitIndexConflictIterator::Create) {

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

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

  CreateBaton* baton = new CreateBaton();

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


  nodegit::Context *nodegitContext = reinterpret_cast<nodegit::Context *>(info.Data().As<External>()->Value());
  std::map<std::string, std::shared_ptr<nodegit::CleanupHandle>> cleanupHandles;

// start convert_from_v8 block
  git_index * from_index = NULL;
from_index = Nan::ObjectWrap::Unwrap<GitIndex>(Nan::To<v8::Object>(info[0]).ToLocalChecked())->GetValue();
// end convert_from_v8 block
          baton->index = from_index;

  Nan::Callback *callback = new Nan::Callback(v8::Local<Function>::Cast(info[info.Length() - 1]));
  CreateWorker *worker = new CreateWorker(baton, callback, cleanupHandles);

             worker->Reference<GitIndex>("index", info[0]);
  
  nodegitContext->QueueWorker(worker);
  return;
}

nodegit::LockMaster GitIndexConflictIterator::CreateWorker::AcquireLocks() {
  nodegit::LockMaster lockMaster(
    /*asyncAction: */true
          ,baton->index
  );

  return lockMaster;
}

void GitIndexConflictIterator::CreateWorker::Execute() {
  git_error_clear();

    int result = git_index_conflict_iterator_new(
&baton->iterator_out,baton->index  );

      baton->error_code = result;

      if (result != GIT_OK && git_error_last()->klass != GIT_ERROR_NONE) {
        baton->error = git_error_dup(git_error_last());
      }

}

void GitIndexConflictIterator::CreateWorker::HandleErrorCallback() {
  if (!GetIsCancelled()) {
    v8::Local<v8::Object> err = Nan::To<v8::Object>(Nan::Error(ErrorMessage())).ToLocalChecked();
    Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("IndexConflictIterator.create").ToLocalChecked());
    v8::Local<v8::Value> argv[1] = {
      err
    };
    callback->Call(1, argv, async_resource);
  }

  if (baton->error) {
    if (baton->error->message) {
      free((void *)baton->error->message);
    }

    free((void *)baton->error);
  }

      git_index_conflict_iterator_free(baton->iterator_out);

  delete baton;
}

void GitIndexConflictIterator::CreateWorker::HandleOKCallback() {
    if (baton->error_code == GIT_OK) {
    v8::Local<v8::Value> v8ConversionSlot;
// start convert_to_v8 block
    if (baton->iterator_out != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
            Nan::Set(owners, Nan::New<v8::Number>(owners->Length()), Nan::To<v8::Object>(this->GetFromPersistent("index")).ToLocalChecked());
             v8ConversionSlot = GitIndexConflictIterator::New(
        baton->iterator_out,
        true
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
      v8::Local<v8::Value> result = v8ConversionSlot;
     
    v8::Local<v8::Value> argv[2] = {
      Nan::Null(),
      result
    };
    callback->Call(2, argv, async_resource);
  } else {
    if (baton->error) {
      v8::Local<v8::Object> err;
      if (baton->error->message) {
        err = Nan::To<v8::Object>(Nan::Error(baton->error->message)).ToLocalChecked();
      } else {
        err = Nan::To<v8::Object>(Nan::Error("Method create has thrown an error.")).ToLocalChecked();
      }
      Nan::Set(err, Nan::New("errno").ToLocalChecked(), Nan::New(baton->error_code));
      Nan::Set(err, Nan::New("errorFunction").ToLocalChecked(), Nan::New("IndexConflictIterator.create").ToLocalChecked());
      v8::Local<v8::Value> argv[1] = {
        err
      };
      callback->Call(1, argv, async_resource);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else if (baton->error_code < 0) {
      bool callbackFired = false;
      if (!callbackErrorHandle.IsEmpty()) {
        v8::Local<v8::Value> maybeError = Nan::New(callbackErrorHandle);
        if (!maybeError->IsNull() && !maybeError->IsUndefined()) {
          v8::Local<v8::Value> argv[1] = {
            maybeError
          };
          callback->Call(1, argv, async_resource);
          callbackFired = true;
        }
      }

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

        git_index_conflict_iterator_free(baton->iterator_out);
  }


  delete baton;
}

   
/*
        * @return IndexEntry ancestor_out    * @return IndexEntry our_out    * @return IndexEntry their_out    */
NAN_METHOD(GitIndexConflictIterator::Next) {
  Nan::EscapableHandleScope scope;

      const git_index_entry * ancestor_out = 0;
      const git_index_entry * our_out = 0;
      const git_index_entry * their_out = 0;

  git_error_clear();

  { // lock master scope start
    nodegit::LockMaster lockMaster(
      /*asyncAction: */false
            ,
              Nan::ObjectWrap::Unwrap<GitIndexConflictIterator>(info.This())->GetValue()
    );

 int result =     git_index_conflict_next(
&          ancestor_out
,&          our_out
,&          their_out
,          Nan::ObjectWrap::Unwrap<GitIndexConflictIterator>(info.This())->GetValue()
    );


      v8::Local<v8::Value> v8ConversionSlot;
        v8::Local<Object> toReturn = Nan::New<Object>();
// start convert_to_v8 block
    if (ancestor_out != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
         Nan::Set(owners, owners->Length(), info.This());
          v8ConversionSlot = GitIndexEntry::New(
        ancestor_out,
        false
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
          Nan::Set(toReturn, Nan::New("ancestor_out").ToLocalChecked(), v8ConversionSlot);
// start convert_to_v8 block
    if (our_out != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
         Nan::Set(owners, owners->Length(), info.This());
          v8ConversionSlot = GitIndexEntry::New(
        our_out,
        false
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
          Nan::Set(toReturn, Nan::New("our_out").ToLocalChecked(), v8ConversionSlot);
// start convert_to_v8 block
    if (their_out != NULL) {
      v8::Local<v8::Array> owners = Nan::New<Array>(0);
         Nan::Set(owners, owners->Length(), info.This());
          v8ConversionSlot = GitIndexEntry::New(
        their_out,
        false
          , owners
       );
   }
  else {
    v8ConversionSlot = Nan::Null();
  }
  // end convert_to_v8 block
          Nan::Set(toReturn, Nan::New("their_out").ToLocalChecked(), v8ConversionSlot);
        return info.GetReturnValue().Set(scope.Escape(toReturn));
  }
}
    // force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<GitIndexConflictIteratorTraits>;
 