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

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


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

#include "../include/diff.h"
#include "../include/diff_delta.h"
#include "../include/diff_perfdata.h"
#include "../include/repository.h"
#include "../include/tree.h"
#include "../include/diff_options.h"

#include <iostream>

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

GitDiff::GitDiff(git_diff *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitDiff::~GitDiff()
{
  if (this->selfFreeing) {
    git_diff_free(this->raw);
  }
}

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

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

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

  NODE_SET_PROTOTYPE_METHOD(tpl, "getDelta", GetDelta);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getPerfdata", GetPerfdata);
  NODE_SET_PROTOTYPE_METHOD(tpl, "numDeltas", NumDeltas);
  NODE_SET_METHOD(tpl, "treeToTree", TreeToTree);

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

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

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

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

  NanReturnValue(args.This());
}

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

git_diff *GitDiff::GetValue()
{
  return this->raw;
}

git_diff **GitDiff::GetRefValue()
{
  return &this->raw;
}


/*
   * @param Number idx
     * @return DiffDelta  result    */
NAN_METHOD(GitDiff::GetDelta)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  size_t from_idx;
  from_idx = (size_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  const git_diff_delta * result = git_diff_get_delta(
                                    ObjectWrap::Unwrap<GitDiff>(args.This())->GetValue()
                                    ,from_idx
                                  );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

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

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @param DiffPerfdata callback
   */
NAN_METHOD(GitDiff::GetPerfdata)
{
  NanScope();

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

  GetPerfdataBaton* baton = new GetPerfdataBaton;

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

  baton->diff = ObjectWrap::Unwrap<GitDiff>(args.This())->GetValue();

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitDiff::GetPerfdataWorker::Execute()
{
  int result = git_diff_get_perfdata(
                 baton->out,baton->diff    );

  baton->error_code = result;

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

}

void GitDiff::GetPerfdataWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->out != NULL) {
      // GitDiffPerfdata baton->out
      to = GitDiffPerfdata::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 Number  result    */
NAN_METHOD(GitDiff::NumDeltas)
{
  NanEscapableScope();

  size_t result = git_diff_num_deltas(
                    ObjectWrap::Unwrap<GitDiff>(args.This())->GetValue()
                  );

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

/*
  * @param Repository repo
   * @param Tree old_tree
   * @param Tree new_tree
   * @param DiffOptions opts
    * @param Diff callback
   */
NAN_METHOD(GitDiff::TreeToTree)
{
  NanScope();

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

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

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

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

  TreeToTreeBaton* baton = new TreeToTreeBaton;

  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
  git_tree * from_old_tree;
  from_old_tree = ObjectWrap::Unwrap<GitTree>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->old_tree = from_old_tree;
// start convert_from_v8 block
  git_tree * from_new_tree;
  from_new_tree = ObjectWrap::Unwrap<GitTree>(args[2]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->new_tree = from_new_tree;
// start convert_from_v8 block
  const git_diff_options * from_opts;

  if (args[3]->IsObject()) {
    from_opts = ObjectWrap::Unwrap<GitDiffOptions>(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]));
  TreeToTreeWorker *worker = new TreeToTreeWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("repo", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("old_tree", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("new_tree", args[2]->ToObject());
  if (!args[3]->IsUndefined() && !args[3]->IsNull())
    worker->SaveToPersistent("opts", args[3]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitDiff::TreeToTreeWorker::Execute()
{
  int result = git_diff_tree_to_tree(
                 &baton->diff,baton->repo,baton->old_tree,baton->new_tree,baton->opts    );

  baton->error_code = result;

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

}

void GitDiff::TreeToTreeWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->diff != NULL) {
      // GitDiff baton->diff
      to = GitDiff::New((void *)baton->diff, 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> GitDiff::constructor_template;
