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

#include "../include/patch.h"
#include "../include/blob.h"
#include "../include/diff_options.h"
#include "../include/diff.h"
#include "../include/diff_delta.h"
#include "../include/diff_hunk.h"
#include "../include/diff_line.h"

#include <iostream>

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

GitPatch::GitPatch(git_patch *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitPatch::~GitPatch()
{
  if (this->selfFreeing) {
    git_patch_free(this->raw);
  }
}

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

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

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

  NODE_SET_METHOD(tpl, "fromBlobAndBuffer", FromBlobAndBuffer);
  NODE_SET_METHOD(tpl, "fromBlobs", FromBlobs);
  NODE_SET_METHOD(tpl, "fromDiff", FromDiff);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getDelta", GetDelta);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getHunk", GetHunk);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getLineInHunk", GetLineInHunk);
  NODE_SET_PROTOTYPE_METHOD(tpl, "numHunks", NumHunks);
  NODE_SET_PROTOTYPE_METHOD(tpl, "numLinesInHunk", NumLinesInHunk);
  NODE_SET_PROTOTYPE_METHOD(tpl, "size", Size);

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

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

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

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

  NanReturnValue(args.This());
}

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

git_patch *GitPatch::GetValue()
{
  return this->raw;
}

git_patch **GitPatch::GetRefValue()
{
  return &this->raw;
}


/*
  * @param Blob old_blob
   * @param String old_as_path
   * @param String buffer
   * @param Number buffer_len
   * @param String buffer_as_path
   * @param DiffOptions opts
    * @param Patch callback
   */
NAN_METHOD(GitPatch::FromBlobAndBuffer)
{
  NanScope();

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

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

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

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

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

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

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

  FromBlobAndBufferBaton* baton = new FromBlobAndBufferBaton;

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

// start convert_from_v8 block
  const git_blob * from_old_blob;
  from_old_blob = ObjectWrap::Unwrap<GitBlob>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->old_blob = from_old_blob;
// start convert_from_v8 block
  const char * from_old_as_path;

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

  String::Utf8Value buffer(args[2]->ToString());
  from_buffer = (const char *) strdup(*buffer);
// end convert_from_v8 block
  baton->buffer = from_buffer;
// start convert_from_v8 block
  size_t from_buffer_len;
  from_buffer_len = (size_t)   args[3]->ToNumber()->Value();
// end convert_from_v8 block
  baton->buffer_len = from_buffer_len;
// start convert_from_v8 block
  const char * from_buffer_as_path;

  String::Utf8Value buffer_as_path(args[4]->ToString());
  from_buffer_as_path = (const char *) strdup(*buffer_as_path);
// end convert_from_v8 block
  baton->buffer_as_path = from_buffer_as_path;
// start convert_from_v8 block
  const git_diff_options * from_opts;
  from_opts = ObjectWrap::Unwrap<GitDiffOptions>(args[5]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->opts = from_opts;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[6]));
  FromBlobAndBufferWorker *worker = new FromBlobAndBufferWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("old_blob", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("old_as_path", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("buffer", args[2]->ToObject());
  if (!args[3]->IsUndefined() && !args[3]->IsNull())
    worker->SaveToPersistent("buffer_len", args[3]->ToObject());
  if (!args[4]->IsUndefined() && !args[4]->IsNull())
    worker->SaveToPersistent("buffer_as_path", args[4]->ToObject());
  if (!args[5]->IsUndefined() && !args[5]->IsNull())
    worker->SaveToPersistent("opts", args[5]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitPatch::FromBlobAndBufferWorker::Execute()
{
  int result = git_patch_from_blob_and_buffer(
                 &baton->out,baton->old_blob,baton->old_as_path,baton->buffer,baton->buffer_len,baton->buffer_as_path,baton->opts    );

  baton->error_code = result;

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

}

void GitPatch::FromBlobAndBufferWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->out != NULL) {
      // GitPatch baton->out
      to = GitPatch::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->old_as_path);
  free((void *)baton->buffer);
  free((void *)baton->buffer_as_path);

  delete baton;
}

/*
  * @param Blob old_blob
   * @param String old_as_path
   * @param Blob new_blob
   * @param String new_as_path
   * @param DiffOptions opts
    * @param Patch callback
   */
NAN_METHOD(GitPatch::FromBlobs)
{
  NanScope();

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

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

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

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

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

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

  FromBlobsBaton* baton = new FromBlobsBaton;

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

// start convert_from_v8 block
  const git_blob * from_old_blob;
  from_old_blob = ObjectWrap::Unwrap<GitBlob>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->old_blob = from_old_blob;
// start convert_from_v8 block
  const char * from_old_as_path;

  String::Utf8Value old_as_path(args[1]->ToString());
  from_old_as_path = (const char *) strdup(*old_as_path);
// end convert_from_v8 block
  baton->old_as_path = from_old_as_path;
// start convert_from_v8 block
  const git_blob * from_new_blob;
  from_new_blob = ObjectWrap::Unwrap<GitBlob>(args[2]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->new_blob = from_new_blob;
// start convert_from_v8 block
  const char * from_new_as_path;

  String::Utf8Value new_as_path(args[3]->ToString());
  from_new_as_path = (const char *) strdup(*new_as_path);
// end convert_from_v8 block
  baton->new_as_path = from_new_as_path;
// start convert_from_v8 block
  const git_diff_options * from_opts;
  from_opts = ObjectWrap::Unwrap<GitDiffOptions>(args[4]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->opts = from_opts;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[5]));
  FromBlobsWorker *worker = new FromBlobsWorker(baton, callback);
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("old_blob", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("old_as_path", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("new_blob", args[2]->ToObject());
  if (!args[3]->IsUndefined() && !args[3]->IsNull())
    worker->SaveToPersistent("new_as_path", args[3]->ToObject());
  if (!args[4]->IsUndefined() && !args[4]->IsNull())
    worker->SaveToPersistent("opts", args[4]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitPatch::FromBlobsWorker::Execute()
{
  int result = git_patch_from_blobs(
                 &baton->out,baton->old_blob,baton->old_as_path,baton->new_blob,baton->new_as_path,baton->opts    );

  baton->error_code = result;

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

}

void GitPatch::FromBlobsWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->out != NULL) {
      // GitPatch baton->out
      to = GitPatch::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->old_as_path);
  free((void *)baton->new_as_path);

  delete baton;
}

/*
  * @param Diff diff
   * @param Number idx
     * @return Patch out    */
NAN_METHOD(GitPatch::FromDiff)
{
  NanEscapableScope();

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

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

  git_patch * out = 0;
// start convert_from_v8 block
  git_diff * from_diff;
  from_diff = ObjectWrap::Unwrap<GitDiff>(args[0]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  size_t from_idx;
  from_idx = (size_t)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_patch_from_diff(
                 &out
                 ,from_diff
                 ,from_idx
               );
  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) {
    // GitPatch out
    to = GitPatch::New((void *)out, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return DiffDelta  result    */
NAN_METHOD(GitPatch::GetDelta)
{
  NanEscapableScope();

  const git_diff_delta * result = git_patch_get_delta(
                                    ObjectWrap::Unwrap<GitPatch>(args.This())->GetValue()
                                  );
  // 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 Number hunk_idx
     * @return DiffHunk out    * @return Number lines_in_hunk    */
NAN_METHOD(GitPatch::GetHunk)
{
  NanEscapableScope();

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

  const git_diff_hunk * out = 0;
  size_t lines_in_hunk = 0;
// start convert_from_v8 block
  size_t from_hunk_idx;
  from_hunk_idx = (size_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_patch_get_hunk(
                 &out
                 ,&lines_in_hunk
                 ,ObjectWrap::Unwrap<GitPatch>(args.This())->GetValue()
                 ,from_hunk_idx
               );
  if (result != GIT_OK) {

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

  Handle<Value> to;
  Handle<Object> toReturn = NanNew<Object>();
// start convert_to_v8 block

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

// end convert_to_v8 block
  toReturn->Set(NanNew<String>("hunk"), to);
// start convert_to_v8 block
  to = NanNew<Number>(lines_in_hunk);
  // end convert_to_v8 block
  toReturn->Set(NanNew<String>("lines_in_hunk"), to);
  NodeGitPsueodoNanReturnEscapingValue(toReturn);
}

/*
    * @param Number hunk_idx
   * @param Number line_of_hunk
     * @return DiffLine out    */
NAN_METHOD(GitPatch::GetLineInHunk)
{
  NanEscapableScope();

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

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

  const git_diff_line * out = 0;
// start convert_from_v8 block
  size_t from_hunk_idx;
  from_hunk_idx = (size_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
// start convert_from_v8 block
  size_t from_line_of_hunk;
  from_line_of_hunk = (size_t)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_patch_get_line_in_hunk(
                 &out
                 ,ObjectWrap::Unwrap<GitPatch>(args.This())->GetValue()
                 ,from_hunk_idx
                 ,from_line_of_hunk
               );
  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) {
    // GitDiffLine out
    to = GitDiffLine::New((void *)out, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitPatch::NumHunks)
{
  NanEscapableScope();

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

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

/*
   * @param Number hunk_idx
     * @return Number  result    */
NAN_METHOD(GitPatch::NumLinesInHunk)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  size_t from_hunk_idx;
  from_hunk_idx = (size_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_patch_num_lines_in_hunk(
                 ObjectWrap::Unwrap<GitPatch>(args.This())->GetValue()
                 ,from_hunk_idx
               );

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

/*
   * @param Number include_context
   * @param Number include_hunk_headers
   * @param Number include_file_headers
     * @return Number  result    */
NAN_METHOD(GitPatch::Size)
{
  NanEscapableScope();

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

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

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

// start convert_from_v8 block
  int from_include_context;
  from_include_context = (int)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
// start convert_from_v8 block
  int from_include_hunk_headers;
  from_include_hunk_headers = (int)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
// start convert_from_v8 block
  int from_include_file_headers;
  from_include_file_headers = (int)   args[2]->ToNumber()->Value();
// end convert_from_v8 block
  size_t result = git_patch_size(
                    ObjectWrap::Unwrap<GitPatch>(args.This())->GetValue()
                    ,from_include_context
                    ,from_include_hunk_headers
                    ,from_include_file_headers
                  );

  Handle<Value> to;
// start convert_to_v8 block
  to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}
Persistent<Function> GitPatch::constructor_template;
