// This is a generated file, modify: generate/templates/class_content.cc.
#include <nan.h>
#include <string.h>

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


#include "../include/functions/copy.h"
#include "../include/macros.h"
#include "../include/merge_head.h"

  #include "../include/merge_head.h"
  #include "../include/repository.h"
  #include "../include/oid.h"
  #include "../include/reference.h"
 
#include <iostream>

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

  GitMergeHead::GitMergeHead(git_merge_head *raw, bool selfFreeing) {
    this->raw = raw;
    this->selfFreeing = selfFreeing;
  }

  GitMergeHead::~GitMergeHead() {
      if (this->selfFreeing) {
        git_merge_head_free(this->raw);
      }
   }

  void GitMergeHead::InitializeComponent(Handle<v8::Object> target) {
    NanScope();

    Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(JSNewFunction);

    tpl->InstanceTemplate()->SetInternalFieldCount(1);
    tpl->SetClassName(NanNew<String>("MergeHead"));

           NODE_SET_METHOD(tpl, "fromFetchhead", FromFetchhead);
             NODE_SET_METHOD(tpl, "fromId", FromId);
             NODE_SET_METHOD(tpl, "fromRef", FromRef);
            NODE_SET_PROTOTYPE_METHOD(tpl, "id", Id);
    
    Local<Function> _constructor_template = tpl->GetFunction();
    NanAssignPersistent(constructor_template, _constructor_template);
    target->Set(NanNew<String>("MergeHead"), _constructor_template);
  }

  NAN_METHOD(GitMergeHead::JSNewFunction) {
    NanScope();

    if (args.Length() == 0 || !args[0]->IsExternal()) {
         return NanThrowError("A new GitMergeHead cannot be instantiated.");
     }

    GitMergeHead* object = new GitMergeHead(static_cast<git_merge_head *>(Handle<External>::Cast(args[0])->Value()), args[1]->BooleanValue());
    object->Wrap(args.This());

    NanReturnValue(args.This());
  }

  Handle<Value> GitMergeHead::New(void *raw, bool selfFreeing) {
    NanEscapableScope();
    Handle<Value> argv[2] = { NanNew<External>((void *)raw), NanNew<Boolean>(selfFreeing) };
    return NanEscapeScope(NanNew<Function>(GitMergeHead::constructor_template)->NewInstance(2, argv));
  }

  git_merge_head *GitMergeHead::GetValue() {
    return this->raw;
  }

  git_merge_head **GitMergeHead::GetRefValue() {
    return &this->raw;
  }

 
/*
  * @param Repository repo
   * @param String branch_name
   * @param String remote_url
   * @param Oid oid
    * @param MergeHead callback
   */
NAN_METHOD(GitMergeHead::FromFetchhead) {
  NanScope();

  if (args.Length() == 0 || !args[0]->IsObject()) {
    return NanThrowError("Repository repo is required.");
  }

  if (args.Length() == 1 || !args[1]->IsString()) {
    return NanThrowError("String branch_name is required.");
  }

  if (args.Length() == 2 || !args[2]->IsString()) {
    return NanThrowError("String remote_url is required.");
  }

  if (args.Length() == 3
    || (!args[3]->IsObject() && !args[3]->IsString())) {
    return NanThrowError("Oid oid is required.");
  }

  if (args.Length() == 4 || !args[4]->IsFunction()) {
    return NanThrowError("Callback is required and must be a Function.");
  }

  FromFetchheadBaton* baton = new FromFetchheadBaton;

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

// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->repo = from_repo;
// start convert_from_v8 block
  const char * from_branch_name;

  String::Utf8Value branch_name(args[1]->ToString());
  from_branch_name = (const char *) strdup(*branch_name);
// end convert_from_v8 block
  baton->branch_name = from_branch_name;
// start convert_from_v8 block
  const char * from_remote_url;

  String::Utf8Value remote_url(args[2]->ToString());
  from_remote_url = (const char *) strdup(*remote_url);
// end convert_from_v8 block
  baton->remote_url = from_remote_url;
// start convert_from_v8 block
  const git_oid * from_oid;
  if (args[3]->IsString()) {
    // Try and parse in a string to a git_oid
    String::Utf8Value oidString(args[3]->ToString());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (giterr_last()) {
        return NanThrowError(giterr_last()->message);
      } else {
        return NanThrowError("Unknown Error");
      }
    }

    from_oid = oidOut;
  }
  else {
    from_oid = ObjectWrap::Unwrap<GitOid>(args[3]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->oid = from_oid;
  baton->oidNeedsFree = args[3]->IsString();

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[4]));
  FromFetchheadWorker *worker = new FromFetchheadWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("repo", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("branch_name", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("remote_url", args[2]->ToObject());
  if (!args[3]->IsUndefined() && !args[3]->IsNull())
    worker->SaveToPersistent("oid", args[3]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMergeHead::FromFetchheadWorker::Execute() {
  int result = git_merge_head_from_fetchhead(
&baton->out,baton->repo,baton->branch_name,baton->remote_url,baton->oid    );

  baton->error_code = result;

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

}

void GitMergeHead::FromFetchheadWorker::HandleOKCallback() {
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block
  
  if (baton->out != NULL) {
    // GitMergeHead baton->out
       to = GitMergeHead::New((void *)baton->out, false);
   }
  else {
    to = NanNull();
  }

 // end convert_to_v8 block
    Handle<Value> result = to;
    Handle<Value> argv[2] = {
      NanNull(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      Handle<Value> argv[1] = {
        NanError(baton->error->message)
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else {
      callback->Call(0, NULL);
    }

  }

  if (try_catch.HasCaught()) {
    node::FatalException(try_catch);
  }

  free((void *)baton->branch_name);
  free((void *)baton->remote_url);
  if (baton->oidNeedsFree) {
    baton->oidNeedsFree = false;
    free((void *)baton->oid);
  }

  delete baton;
}
  
/*
  * @param Repository repo
   * @param Oid id
    * @param MergeHead callback
   */
NAN_METHOD(GitMergeHead::FromId) {
  NanScope();

  if (args.Length() == 0 || !args[0]->IsObject()) {
    return NanThrowError("Repository repo is required.");
  }

  if (args.Length() == 1
    || (!args[1]->IsObject() && !args[1]->IsString())) {
    return NanThrowError("Oid id is required.");
  }

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

  FromIdBaton* baton = new FromIdBaton;

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

// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->repo = from_repo;
// start convert_from_v8 block
  const git_oid * from_id;
  if (args[1]->IsString()) {
    // Try and parse in a string to a git_oid
    String::Utf8Value oidString(args[1]->ToString());
    git_oid *oidOut = (git_oid *)malloc(sizeof(git_oid));

    if (git_oid_fromstr(oidOut, (const char *) strdup(*oidString)) != GIT_OK) {
      free(oidOut);

      if (giterr_last()) {
        return NanThrowError(giterr_last()->message);
      } else {
        return NanThrowError("Unknown Error");
      }
    }

    from_id = oidOut;
  }
  else {
    from_id = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->id = from_id;
  baton->idNeedsFree = args[1]->IsString();

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[2]));
  FromIdWorker *worker = new FromIdWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("repo", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("id", args[1]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMergeHead::FromIdWorker::Execute() {
  int result = git_merge_head_from_id(
&baton->out,baton->repo,baton->id    );

  baton->error_code = result;

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

}

void GitMergeHead::FromIdWorker::HandleOKCallback() {
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block
  
  if (baton->out != NULL) {
    // GitMergeHead baton->out
       to = GitMergeHead::New((void *)baton->out, false);
   }
  else {
    to = NanNull();
  }

 // end convert_to_v8 block
    Handle<Value> result = to;
    Handle<Value> argv[2] = {
      NanNull(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      Handle<Value> argv[1] = {
        NanError(baton->error->message)
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else {
      callback->Call(0, NULL);
    }

  }

  if (try_catch.HasCaught()) {
    node::FatalException(try_catch);
  }

  if (baton->idNeedsFree) {
    baton->idNeedsFree = false;
    free((void *)baton->id);
  }

  delete baton;
}
  
/*
  * @param Repository repo
   * @param Reference ref
    * @param MergeHead callback
   */
NAN_METHOD(GitMergeHead::FromRef) {
  NanScope();

  if (args.Length() == 0 || !args[0]->IsObject()) {
    return NanThrowError("Repository repo is required.");
  }

  if (args.Length() == 1 || !args[1]->IsObject()) {
    return NanThrowError("Reference ref is required.");
  }

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

  FromRefBaton* baton = new FromRefBaton;

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

// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->repo = from_repo;
// start convert_from_v8 block
  const git_reference * from_ref;
  from_ref = ObjectWrap::Unwrap<GitRefs>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->ref = from_ref;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[2]));
  FromRefWorker *worker = new FromRefWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("repo", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("ref", args[1]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMergeHead::FromRefWorker::Execute() {
  int result = git_merge_head_from_ref(
&baton->out,baton->repo,baton->ref    );

  baton->error_code = result;

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

}

void GitMergeHead::FromRefWorker::HandleOKCallback() {
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block
  
  if (baton->out != NULL) {
    // GitMergeHead baton->out
       to = GitMergeHead::New((void *)baton->out, false);
   }
  else {
    to = NanNull();
  }

 // end convert_to_v8 block
    Handle<Value> result = to;
    Handle<Value> argv[2] = {
      NanNull(),
      result
    };
    callback->Call(2, argv);
  } else {
    if (baton->error) {
      Handle<Value> argv[1] = {
        NanError(baton->error->message)
      };
      callback->Call(1, argv);
      if (baton->error->message)
        free((void *)baton->error->message);
      free((void *)baton->error);
    } else {
      callback->Call(0, NULL);
    }

  }

  if (try_catch.HasCaught()) {
    node::FatalException(try_catch);
  }


  delete baton;
}
   
/*
     * @return Oid  result    */
NAN_METHOD(GitMergeHead::Id) {
  NanEscapableScope();

  const git_oid * result = git_merge_head_id(
ObjectWrap::Unwrap<GitMergeHead>(args.This())->GetValue()
  );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block
  
  if (result != NULL) {
    // GitOid result
       to = GitOid::New((void *)result, false);
   }
  else {
    to = NanNull();
  }

 // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}
      Persistent<Function> GitMergeHead::constructor_template;
 