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

#include "../include/oid.h"
#include "../include/repository.h"
#include "../include/index.h"
#include "../include/commit.h"
#include "../include/merge_options.h"
#include "../include/merge_file_input.h"
#include "../include/tree.h"

#include <iostream>

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


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

  Local<Object> object = NanNew<Object>();

  NODE_SET_METHOD(object, "base", Base);
  NODE_SET_METHOD(object, "commits", Commits);
  NODE_SET_METHOD(object, "fileInitInput", FileInitInput);
  NODE_SET_METHOD(object, "initOptions", InitOptions);
  NODE_SET_METHOD(object, "trees", Trees);

  target->Set(NanNew<String>("Merge"), object);
}


/*
  * @param Repository repo
   * @param Oid one
   * @param Oid two
    * @param Oid callback
   */
NAN_METHOD(GitMerge::Base)
{
  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 one is required.");
  }

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

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

  BaseBaton* baton = new BaseBaton;

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

  baton->out = (git_oid *)malloc(sizeof(git_oid ));
// 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_one;
  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_one = oidOut;
  } else {
    from_one = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->one = from_one;
  baton->oneNeedsFree = args[1]->IsString();
// start convert_from_v8 block
  const git_oid * from_two;
  if (args[2]->IsString()) {
    // Try and parse in a string to a git_oid
    String::Utf8Value oidString(args[2]->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_two = oidOut;
  } else {
    from_two = ObjectWrap::Unwrap<GitOid>(args[2]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->two = from_two;
  baton->twoNeedsFree = args[2]->IsString();

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMerge::BaseWorker::Execute()
{
  int result = git_merge_base(
                 baton->out,baton->repo,baton->one,baton->two    );

  baton->error_code = result;

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

}

void GitMerge::BaseWorker::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);
  }

  if (baton->oneNeedsFree) {
    baton->oneNeedsFree = false;
    free((void *)baton->one);
  }
  if (baton->twoNeedsFree) {
    baton->twoNeedsFree = false;
    free((void *)baton->two);
  }

  delete baton;
}

/*
  * @param Repository repo
   * @param Commit our_commit
   * @param Commit their_commit
   * @param MergeOptions opts
    * @param Index callback
   */
NAN_METHOD(GitMerge::Commits)
{
  NanScope();

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

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

  if (args.Length() == 2 || !args[2]->IsObject()) {
    return NanThrowError("Commit their_commit is required.");
  }

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

  CommitsBaton* baton = new CommitsBaton;

  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_commit * from_our_commit;
  from_our_commit = ObjectWrap::Unwrap<GitCommit>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->our_commit = from_our_commit;
// start convert_from_v8 block
  const git_commit * from_their_commit;
  from_their_commit = ObjectWrap::Unwrap<GitCommit>(args[2]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->their_commit = from_their_commit;
// start convert_from_v8 block
  const git_merge_options * from_opts;

  if (args[3]->IsObject()) {
    from_opts = ObjectWrap::Unwrap<GitMergeOptions>(args[3]->ToObject())->GetValue();
  } else {
    from_opts = 0;
  }

// end convert_from_v8 block
  baton->opts = from_opts;

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMerge::CommitsWorker::Execute()
{
  int result = git_merge_commits(
                 &baton->out,baton->repo,baton->our_commit,baton->their_commit,baton->opts    );

  baton->error_code = result;

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

}

void GitMerge::CommitsWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->out != NULL) {
      // GitIndex baton->out
      to = GitIndex::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 MergeFileInput opts
   * @param Number version
     * @return Number  result    */
NAN_METHOD(GitMerge::FileInitInput)
{
  NanEscapableScope();

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

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

// start convert_from_v8 block
  git_merge_file_input * from_opts;
  from_opts = ObjectWrap::Unwrap<GitMergeFileInput>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  unsigned int from_version;
  from_version = (unsigned int)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_merge_file_init_input(
                 from_opts
                 ,from_version
               );

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

/*
 * @param MergeOptions opts
   * @param Number version
     * @return Number  result    */
NAN_METHOD(GitMerge::InitOptions)
{
  NanEscapableScope();

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

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

// start convert_from_v8 block
  git_merge_options * from_opts;
  from_opts = ObjectWrap::Unwrap<GitMergeOptions>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  unsigned int from_version;
  from_version = (unsigned int)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_merge_init_options(
                 from_opts
                 ,from_version
               );

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

/*
  * @param Repository repo
   * @param Tree ancestor_tree
   * @param Tree our_tree
   * @param Tree their_tree
   * @param MergeOptions opts
    * @param Index callback
   */
NAN_METHOD(GitMerge::Trees)
{
  NanScope();

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

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

  if (args.Length() == 2 || !args[2]->IsObject()) {
    return NanThrowError("Tree our_tree is required.");
  }

  if (args.Length() == 3 || !args[3]->IsObject()) {
    return NanThrowError("Tree their_tree is required.");
  }

  if (args.Length() == 4 || !args[4]->IsObject()) {
    return NanThrowError("MergeOptions opts is required.");
  }

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

  TreesBaton* baton = new TreesBaton;

  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_tree * from_ancestor_tree;
  from_ancestor_tree = ObjectWrap::Unwrap<GitTree>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->ancestor_tree = from_ancestor_tree;
// start convert_from_v8 block
  const git_tree * from_our_tree;
  from_our_tree = ObjectWrap::Unwrap<GitTree>(args[2]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->our_tree = from_our_tree;
// start convert_from_v8 block
  const git_tree * from_their_tree;
  from_their_tree = ObjectWrap::Unwrap<GitTree>(args[3]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->their_tree = from_their_tree;
// start convert_from_v8 block
  const git_merge_options * from_opts;
  from_opts = ObjectWrap::Unwrap<GitMergeOptions>(args[4]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->opts = from_opts;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[5]));
  TreesWorker *worker = new TreesWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("repo", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("ancestor_tree", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("our_tree", args[2]->ToObject());
  if (!args[3]->IsUndefined() && !args[3]->IsNull())
    worker->SaveToPersistent("their_tree", args[3]->ToObject());
  if (!args[4]->IsUndefined() && !args[4]->IsNull())
    worker->SaveToPersistent("opts", args[4]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitMerge::TreesWorker::Execute()
{
  int result = git_merge_trees(
                 &baton->out,baton->repo,baton->ancestor_tree,baton->our_tree,baton->their_tree,baton->opts    );

  baton->error_code = result;

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

}

void GitMerge::TreesWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->out != NULL) {
      // GitIndex baton->out
      to = GitIndex::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;
}
Persistent<Function> GitMerge::constructor_template;
