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

  #include "../include/odb.h"
  #include "../include/odb_object.h"
  #include "../include/oid.h"
 
#include <iostream>

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

  GitOdb::GitOdb(git_odb *raw, bool selfFreeing) {
    this->raw = raw;
    this->selfFreeing = selfFreeing;
  }

  GitOdb::~GitOdb() {
      if (this->selfFreeing) {
        git_odb_free(this->raw);
      }
   }

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

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

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

          NODE_SET_PROTOTYPE_METHOD(tpl, "addDiskAlternate", AddDiskAlternate);
             NODE_SET_METHOD(tpl, "open", Open);
            NODE_SET_PROTOTYPE_METHOD(tpl, "read", Read);
            NODE_SET_PROTOTYPE_METHOD(tpl, "write", Write);
    
    Local<Function> _constructor_template = tpl->GetFunction();
    NanAssignPersistent(constructor_template, _constructor_template);
    target->Set(NanNew<String>("Odb"), _constructor_template);
  }

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

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

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

    NanReturnValue(args.This());
  }

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

  git_odb *GitOdb::GetValue() {
    return this->raw;
  }

  git_odb **GitOdb::GetRefValue() {
    return &this->raw;
  }

  
/*
   * @param String path
     * @return Number  result    */
NAN_METHOD(GitOdb::AddDiskAlternate) {
  NanEscapableScope();

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

// start convert_from_v8 block
  const char * from_path;

  String::Utf8Value path(args[0]->ToString());
  from_path = (const char *) strdup(*path);
// end convert_from_v8 block
  int result = git_odb_add_disk_alternate(
ObjectWrap::Unwrap<GitOdb>(args.This())->GetValue()
,from_path
  );

  Handle<Value> to;
// start convert_to_v8 block
     to = NanNew<Number>(result);
  // end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}
  
/*
  * @param String objects_dir
    * @param Odb callback
   */
NAN_METHOD(GitOdb::Open) {
  NanScope();

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

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

  OpenBaton* baton = new OpenBaton;

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

// start convert_from_v8 block
  const char * from_objects_dir;

  String::Utf8Value objects_dir(args[0]->ToString());
  from_objects_dir = (const char *) strdup(*objects_dir);
// end convert_from_v8 block
  baton->objects_dir = from_objects_dir;

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitOdb::OpenWorker::Execute() {
  int result = git_odb_open(
&baton->out,baton->objects_dir    );

  baton->error_code = result;

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

}

void GitOdb::OpenWorker::HandleOKCallback() {
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block
  
  if (baton->out != NULL) {
    // GitOdb baton->out
       to = GitOdb::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->objects_dir);

  delete baton;
}
  
/*
    * @param Oid id
    * @param OdbObject callback
   */
NAN_METHOD(GitOdb::Read) {
  NanScope();

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

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

  ReadBaton* baton = new ReadBaton;

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

  baton->db = ObjectWrap::Unwrap<GitOdb>(args.This())->GetValue();
// start convert_from_v8 block
  const 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
  baton->id = from_id;
  baton->idNeedsFree = args[0]->IsString();

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitOdb::ReadWorker::Execute() {
  int result = git_odb_read(
&baton->out,baton->db,baton->id    );

  baton->error_code = result;

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

}

void GitOdb::ReadWorker::HandleOKCallback() {
  TryCatch try_catch;

  if (baton->error_code == GIT_OK) {
    Handle<Value> to;
// start convert_to_v8 block
  
  if (baton->out != NULL) {
    // GitOdbObject baton->out
       to = GitOdbObject::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->idNeedsFree) {
    baton->idNeedsFree = false;
    free((void *)baton->id);
  }

  delete baton;
}
  
/*
    * @param Buffer data
   * @param Number len
   * @param Number type
    * @param Oid callback
   */
NAN_METHOD(GitOdb::Write) {
  NanScope();

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

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

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

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

  WriteBaton* baton = new WriteBaton;

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

  baton->out = (git_oid *)malloc(sizeof(git_oid ));
  baton->odb = ObjectWrap::Unwrap<GitOdb>(args.This())->GetValue();
// start convert_from_v8 block
  const void * from_data;

  String::Utf8Value data(args[0]->ToString());
  from_data = (const void *) strdup(*data);
// end convert_from_v8 block
  baton->data = from_data;
// start convert_from_v8 block
  size_t from_len;
  from_len = (size_t)   args[1]->ToNumber()->Value();
// end convert_from_v8 block
  baton->len = from_len;
// start convert_from_v8 block
  git_otype from_type;
  from_type = (git_otype)  (int) args[2]->ToNumber()->Value();
// end convert_from_v8 block
  baton->type = from_type;

  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[3]));
  WriteWorker *worker = new WriteWorker(baton, callback);
  worker->SaveToPersistent("odb", args.This());
  if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("data", args[0]->ToObject());
  if (!args[1]->IsUndefined() && !args[1]->IsNull())
    worker->SaveToPersistent("len", args[1]->ToObject());
  if (!args[2]->IsUndefined() && !args[2]->IsNull())
    worker->SaveToPersistent("type", args[2]->ToObject());

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitOdb::WriteWorker::Execute() {
  int result = git_odb_write(
baton->out,baton->odb,baton->data,baton->len,baton->type    );

  baton->error_code = result;

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

}

void GitOdb::WriteWorker::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);
  }


  delete baton;
}
      Persistent<Function> GitOdb::constructor_template;
 