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

#include "../include/blame.h"
#include "../include/repository.h"
#include "../include/blame_options.h"
#include "../include/blame_hunk.h"

#include <iostream>

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

GitBlame::GitBlame(git_blame *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitBlame::~GitBlame()
{
  if (this->selfFreeing) {
    git_blame_free(this->raw);
  }
}

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

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

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

  NODE_SET_PROTOTYPE_METHOD(tpl, "buffer", Buffer);
  NODE_SET_METHOD(tpl, "file", File);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getHunkByIndex", GetHunkByindex);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getHunkByLine", GetHunkByline);
  NODE_SET_PROTOTYPE_METHOD(tpl, "getHunkCount", GetHunkCount);
  NODE_SET_METHOD(tpl, "initOptions", InitOptions);

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

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

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

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

  NanReturnValue(args.This());
}

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

git_blame *GitBlame::GetValue()
{
  return this->raw;
}

git_blame **GitBlame::GetRefValue()
{
  return &this->raw;
}


/*
    * @param String buffer
   * @param Number buffer_len
    * @param Blame callback
   */
NAN_METHOD(GitBlame::Buffer)
{
  NanScope();

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

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

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

  BufferBaton* baton = new BufferBaton;

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

  baton->reference = ObjectWrap::Unwrap<GitBlame>(args.This())->GetValue();
// start convert_from_v8 block
  const char * from_buffer;

  String::Utf8Value buffer(args[0]->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[1]->ToNumber()->Value();
// end convert_from_v8 block
  baton->buffer_len = from_buffer_len;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[2]));
  BufferWorker *worker = new BufferWorker(baton, callback);
  worker->SaveToPersistent("reference", args.This());
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("buffer", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("buffer_len", args[1]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitBlame::BufferWorker::Execute()
{
  int result = git_blame_buffer(
                 &baton->out,baton->reference,baton->buffer,baton->buffer_len    );

  baton->error_code = result;

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

}

void GitBlame::BufferWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

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

  delete baton;
}

/*
  * @param Repository repo
   * @param String path
   * @param BlameOptions options
    * @param Blame callback
   */
NAN_METHOD(GitBlame::File)
{
  NanScope();

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

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

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

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

  FileBaton* baton = new FileBaton;

  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_path;

  String::Utf8Value path(args[1]->ToString());
  from_path = (const char *) strdup(*path);
// end convert_from_v8 block
  baton->path = from_path;
// start convert_from_v8 block
  git_blame_options * from_options;
  from_options = ObjectWrap::Unwrap<GitBlameOptions>(args[2]->ToObject())->GetValue();
// end convert_from_v8 block
  baton->options = from_options;

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitBlame::FileWorker::Execute()
{
  int result = git_blame_file(
                 &baton->out,baton->repo,baton->path,baton->options    );

  baton->error_code = result;

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

}

void GitBlame::FileWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

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

  delete baton;
}

/*
   * @param Number index
     * @return BlameHunk  result    */
NAN_METHOD(GitBlame::GetHunkByindex)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  uint32_t from_index;
  from_index = (uint32_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  const git_blame_hunk * result = git_blame_get_hunk_byindex(
                                    ObjectWrap::Unwrap<GitBlame>(args.This())->GetValue()
                                    ,from_index
                                  );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

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

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
   * @param Number lineno
     * @return BlameHunk  result    */
NAN_METHOD(GitBlame::GetHunkByline)
{
  NanEscapableScope();

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

// start convert_from_v8 block
  uint32_t from_lineno;
  from_lineno = (uint32_t)   args[0]->ToNumber()->Value();
// end convert_from_v8 block
  const git_blame_hunk * result = git_blame_get_hunk_byline(
                                    ObjectWrap::Unwrap<GitBlame>(args.This())->GetValue()
                                    ,from_lineno
                                  );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

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

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitBlame::GetHunkCount)
{
  NanEscapableScope();

  uint32_t result = git_blame_get_hunk_count(
                      ObjectWrap::Unwrap<GitBlame>(args.This())->GetValue()
                    );

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

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

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

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

// start convert_from_v8 block
  git_blame_options * from_opts;
  from_opts = ObjectWrap::Unwrap<GitBlameOptions>(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_blame_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);
}
Persistent<Function> GitBlame::constructor_template;
