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

#include "../include/wrapper.h"
#include "node_buffer.h"
#include "../include/oid.h"
#include "../include/repository.h"
#include "../include/blob.h"

#include <iostream>

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

GitBlob::GitBlob(git_blob *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitBlob::~GitBlob()
{
  if (this->selfFreeing) {
    git_blob_free(this->raw);
  }
}

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

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

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

  NODE_SET_METHOD(tpl, "createFromBuffer", CreateFrombuffer);
  NODE_SET_METHOD(tpl, "createFromDisk", CreateFromdisk);
  NODE_SET_METHOD(tpl, "createFromWorkdir", CreateFromworkdir);
  NODE_SET_PROTOTYPE_METHOD(tpl, "id", Id);
  NODE_SET_PROTOTYPE_METHOD(tpl, "isBinary", IsBinary);
  NODE_SET_METHOD(tpl, "lookup", Lookup);
  NODE_SET_METHOD(tpl, "lookupPrefix", LookupPrefix);
  NODE_SET_PROTOTYPE_METHOD(tpl, "owner", Owner);
  NODE_SET_PROTOTYPE_METHOD(tpl, "rawcontent", Rawcontent);
  NODE_SET_PROTOTYPE_METHOD(tpl, "rawsize", Rawsize);

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

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

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

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

  NanReturnValue(args.This());
}

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

git_blob *GitBlob::GetValue()
{
  return this->raw;
}

git_blob **GitBlob::GetRefValue()
{
  return &this->raw;
}


/*
 * @param Oid id
   * @param Repository repo
   * @param Buffer buffer
   * @param Number len
     * @return Number  result    */
NAN_METHOD(GitBlob::CreateFrombuffer)
{
  NanEscapableScope();

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

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

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

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

// start convert_from_v8 block
  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
// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const void * from_buffer;

  from_buffer = Buffer::Data(args[2]->ToObject());
// end convert_from_v8 block
// start convert_from_v8 block
  size_t from_len;
  from_len = (size_t)   args[3]->ToNumber()->Value();
// end convert_from_v8 block
  int result = git_blob_create_frombuffer(
                 from_id
                 ,from_repo
                 ,from_buffer
                 ,from_len
               );
  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 Oid id
   * @param Repository repo
   * @param String path
     * @return Number  result    */
NAN_METHOD(GitBlob::CreateFromdisk)
{
  NanEscapableScope();

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

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

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

// start convert_from_v8 block
  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
// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_path;

  String::Utf8Value path(args[2]->ToString());
  from_path = (const char *) strdup(*path);
// end convert_from_v8 block
  int result = git_blob_create_fromdisk(
                 from_id
                 ,from_repo
                 ,from_path
               );
  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 Oid id
   * @param Repository repo
   * @param String relative_path
     * @return Number  result    */
NAN_METHOD(GitBlob::CreateFromworkdir)
{
  NanEscapableScope();

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

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

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

// start convert_from_v8 block
  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
// start convert_from_v8 block
  git_repository * from_repo;
  from_repo = ObjectWrap::Unwrap<GitRepository>(args[1]->ToObject())->GetValue();
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_relative_path;

  String::Utf8Value relative_path(args[2]->ToString());
  from_relative_path = (const char *) strdup(*relative_path);
// end convert_from_v8 block
  int result = git_blob_create_fromworkdir(
                 from_id
                 ,from_repo
                 ,from_relative_path
               );
  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);
}

/*
     * @return Oid  result    */
NAN_METHOD(GitBlob::Id)
{
  NanEscapableScope();

  const git_oid * result = git_blob_id(
                             ObjectWrap::Unwrap<GitBlob>(args.This())->GetValue()
                           );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

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

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitBlob::IsBinary)
{
  NanEscapableScope();

  int result = git_blob_is_binary(
                 ObjectWrap::Unwrap<GitBlob>(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 Oid id
    * @param Blob callback
   */
NAN_METHOD(GitBlob::Lookup)
{
  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 id is required.");
  }

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

  LookupBaton* baton = new LookupBaton;

  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_oid * from_id;
  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_id = oidOut;
  } else {
    from_id = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->id = from_id;
  baton->idNeedsFree = args[1]->IsString();

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitBlob::LookupWorker::Execute()
{
  int result = git_blob_lookup(
                 &baton->blob,baton->repo,baton->id    );

  baton->error_code = result;

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

}

void GitBlob::LookupWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->blob != NULL) {
      // GitBlob baton->blob
      to = GitBlob::New((void *)baton->blob, 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->idNeedsFree) {
    baton->idNeedsFree = false;
    free((void *)baton->id);
  }

  delete baton;
}

/*
  * @param Repository repo
   * @param Oid id
   * @param Number len
    * @param Blob callback
   */
NAN_METHOD(GitBlob::LookupPrefix)
{
  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 id is required.");
  }

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

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

  LookupPrefixBaton* baton = new LookupPrefixBaton;

  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_oid * from_id;
  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_id = oidOut;
  } else {
    from_id = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue();
  }
// end convert_from_v8 block
  baton->id = from_id;
  baton->idNeedsFree = args[1]->IsString();
// start convert_from_v8 block
  size_t from_len;
  from_len = (size_t)   args[2]->ToNumber()->Value();
// end convert_from_v8 block
  baton->len = from_len;

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitBlob::LookupPrefixWorker::Execute()
{
  int result = git_blob_lookup_prefix(
                 &baton->blob,baton->repo,baton->id,baton->len    );

  baton->error_code = result;

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

}

void GitBlob::LookupPrefixWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

    if (baton->blob != NULL) {
      // GitBlob baton->blob
      to = GitBlob::New((void *)baton->blob, 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->idNeedsFree) {
    baton->idNeedsFree = false;
    free((void *)baton->id);
  }

  delete baton;
}

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

  git_repository * result = git_blob_owner(
                              ObjectWrap::Unwrap<GitBlob>(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);
}

/*
     * @return Buffer  result    */
NAN_METHOD(GitBlob::Rawcontent)
{
  NanEscapableScope();

  const void * result = git_blob_rawcontent(
                          ObjectWrap::Unwrap<GitBlob>(args.This())->GetValue()
                        );
  // null checks on pointers
  if (!result) {
    NodeGitPsueodoNanReturnEscapingValue(NanUndefined());
  }

  Handle<Value> to;
// start convert_to_v8 block

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

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
     * @return Number  result    */
NAN_METHOD(GitBlob::Rawsize)
{
  NanEscapableScope();

  git_off_t result = git_blob_rawsize(
                       ObjectWrap::Unwrap<GitBlob>(args.This())->GetValue()
                     );

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