// 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/revwalk.h"

#include "../include/revwalk.h"
#include "../include/oid.h"
#include "../include/repository.h"

#include <iostream>

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

GitRevwalk::GitRevwalk(git_revwalk *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitRevwalk::~GitRevwalk()
{
  if (this->selfFreeing) {
    git_revwalk_free(this->raw);
  }
}

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

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

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

  NODE_SET_PROTOTYPE_METHOD(tpl, "hide", Hide);
  NODE_SET_PROTOTYPE_METHOD(tpl, "hideGlob", HideGlob);
  NODE_SET_PROTOTYPE_METHOD(tpl, "hideHead", HideHead);
  NODE_SET_PROTOTYPE_METHOD(tpl, "hideRef", HideRef);
  NODE_SET_METHOD(tpl, "create", Create);
  NODE_SET_PROTOTYPE_METHOD(tpl, "next", Next);
  NODE_SET_PROTOTYPE_METHOD(tpl, "push", Push);
  NODE_SET_PROTOTYPE_METHOD(tpl, "pushGlob", PushGlob);
  NODE_SET_PROTOTYPE_METHOD(tpl, "pushHead", PushHead);
  NODE_SET_PROTOTYPE_METHOD(tpl, "pushRange", PushRange);
  NODE_SET_PROTOTYPE_METHOD(tpl, "pushRef", PushRef);
  NODE_SET_PROTOTYPE_METHOD(tpl, "repository", Repository);
  NODE_SET_PROTOTYPE_METHOD(tpl, "reset", Reset);
  NODE_SET_PROTOTYPE_METHOD(tpl, "simplifyFirstParent", SimplifyFirstParent);
  NODE_SET_PROTOTYPE_METHOD(tpl, "sorting", Sorting);

  Local<Function> _constructor_template = tpl->GetFunction();
  NanAssignPersistent(constructor_template, _constructor_template);
  target->Set(NanNew<String>("Revwalk"), _constructor_template);
}

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

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

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

  NanReturnValue(args.This());
}

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

git_revwalk *GitRevwalk::GetValue()
{
  return this->raw;
}

git_revwalk **GitRevwalk::GetRefValue()
{
  return &this->raw;
}


/*
   * @param Oid commit_id
     * @return Number  result    */
NAN_METHOD(GitRevwalk::Hide)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const git_oid * from_commit_id;
  if (args[0]->IsString()) {
    // Try and parse in a string to a git_oid
    String::Utf8Value oidString(args[0]->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_commit_id = oidOut;
  } else {
    from_commit_id = ObjectWrap::Unwrap<GitOid>(args[0]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  int result = git_revwalk_hide(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_commit_id
               );
  if (args[0]->IsString()) {
    free(&from_commit_id);
  }

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param String glob
     * @return Number  result    */
NAN_METHOD(GitRevwalk::HideGlob)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_glob;

  String::Utf8Value glob(args[0]->ToString());
  from_glob = (const char *) strdup(*glob);
// end convert_from_v8 block
  int result = git_revwalk_hide_glob(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_glob
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitRevwalk::HideHead)
{
  NanEscapableScope();

  int result = git_revwalk_hide_head(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param String refname
     * @return Number  result    */
NAN_METHOD(GitRevwalk::HideRef)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_refname;

  String::Utf8Value refname(args[0]->ToString());
  from_refname = (const char *) strdup(*refname);
// end convert_from_v8 block
  int result = git_revwalk_hide_ref(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_refname
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
  * @param Repository repo
     * @return Revwalk out    */
NAN_METHOD(GitRevwalk::Create)
{
  NanEscapableScope();

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

  git_revwalk * out = 0;
// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  int result = git_revwalk_new(
                 &out
                 ,from_repo
               );
  if (result != GIT_OK) {

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

  Handle<Value> to;
// start convert_to_v8 block

  if (out != NULL) {
    // GitRevwalk out
    to = GitRevwalk::New((void *)out, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @param Oid callback
   */
NAN_METHOD(GitRevwalk::Next)
{
  NanScope();

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

  NextBaton* baton = new NextBaton;

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

  baton->out = (git_oid *)malloc(sizeof(git_oid ));
  baton->walk = ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue();

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[0]));
  NextWorker *worker = new NextWorker(baton, callback);
  worker->SaveToPersistent("walk", args.This());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitRevwalk::NextWorker::Execute()
{
  int result = git_revwalk_next(
                 baton->out,baton->walk    );

  baton->error_code = result;

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

}

void GitRevwalk::NextWorker::HandleOKCallback()
{
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block

    if (baton->out != NULL) {
      // GitOid baton->out
      to = GitOid::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;
}

/*
   * @param Oid id
     * @return Number  result    */
NAN_METHOD(GitRevwalk::Push)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const git_oid * from_id;
  if (args[0]->IsString()) {
    // Try and parse in a string to a git_oid
    String::Utf8Value oidString(args[0]->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[0]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  int result = git_revwalk_push(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_id
               );
  if (args[0]->IsString()) {
    free(&from_id);
  }

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param String glob
     * @return Number  result    */
NAN_METHOD(GitRevwalk::PushGlob)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_glob;

  String::Utf8Value glob(args[0]->ToString());
  from_glob = (const char *) strdup(*glob);
// end convert_from_v8 block
  int result = git_revwalk_push_glob(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_glob
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitRevwalk::PushHead)
{
  NanEscapableScope();

  int result = git_revwalk_push_head(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param String range
     * @return Number  result    */
NAN_METHOD(GitRevwalk::PushRange)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_range;

  String::Utf8Value range(args[0]->ToString());
  from_range = (const char *) strdup(*range);
// end convert_from_v8 block
  int result = git_revwalk_push_range(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_range
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param String refname
     * @return Number  result    */
NAN_METHOD(GitRevwalk::PushRef)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_refname;

  String::Utf8Value refname(args[0]->ToString());
  from_refname = (const char *) strdup(*refname);
// end convert_from_v8 block
  int result = git_revwalk_push_ref(
                 ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                 ,from_refname
               );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Repository  result    */
NAN_METHOD(GitRevwalk::Repository)
{
  NanEscapableScope();

  git_repository * result = git_revwalk_repository(
                              ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
                            );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

  if (result != NULL) {
    // GitRepository result
    to = GitRepository::New((void *)result, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     */
NAN_METHOD(GitRevwalk::Reset)
{
  NanEscapableScope();

  git_revwalk_reset(
    ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
  );
  NanReturnUndefined();
}

/*
     */
NAN_METHOD(GitRevwalk::SimplifyFirstParent)
{
  NanEscapableScope();

  git_revwalk_simplify_first_parent(
    ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
  );
  NanReturnUndefined();
}

/*
   * @param Number sort_mode
     */
NAN_METHOD(GitRevwalk::Sorting)
{
  NanEscapableScope();

  if (args.Length() == 0 || !args[0]->IsNumber()) {
    return NanThrowError("Number sort_mode is required.");
  }

// start convert_from_v8 block
  unsigned int from_sort_mode;
  from_sort_mode = (unsigned int)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  git_revwalk_sorting(
    ObjectWrap::Unwrap<GitRevwalk>(args.This())->GetValue()
    ,from_sort_mode
  );
  NanReturnUndefined();
}
Persistent<Function> GitRevwalk::constructor_template;
