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

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

#include "../include/functions/copy.h"
#include "../include/tree.h"

#include "../include/tree.h"
#include "../include/repository.h"
#include "../include/tree_entry.h"
#include "../include/object.h"
#include "../include/treebuilder.h"
#include "../include/oid.h"

using namespace v8;
using namespace node;

GitTree::GitTree(git_tree *raw) {
  this->raw = raw;
}

GitTree::~GitTree() {
    git_tree_free(this->raw);
  }

void GitTree::Initialize(Handle<v8::Object> target) {
  NanScope();

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

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

              NODE_SET_METHOD(tpl, "lookup", Lookup);
                        NODE_SET_PROTOTYPE_METHOD(tpl, "entrycount", Entrycount);
                        NODE_SET_PROTOTYPE_METHOD(tpl, "entryByname", EntryByname);
                        NODE_SET_PROTOTYPE_METHOD(tpl, "entryByindex", EntryByindex);
                        NODE_SET_PROTOTYPE_METHOD(tpl, "entryBypath", EntryBypath);
            
  
  Local<Function> _constructor_template = tpl->GetFunction();
  NanAssignPersistent(constructor_template, _constructor_template);
  target->Set(NanNew<String>("Tree"), _constructor_template);
}

NAN_METHOD(GitTree::New) {
  NanScope();

  if (args.Length() == 0 || !args[0]->IsExternal()) {
    return NanThrowError("git_tree is required.");
  }
  GitTree* object = new GitTree(static_cast<git_tree *>(Handle<External>::Cast(args[0])->Value()));
  object->Wrap(args.This());

  NanReturnValue(args.This());
}

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

git_tree *GitTree::GetValue() {
  return this->raw;
}

            /**
        * @param Repository repo
            * @param Oid id
            * @param Tree callback
  */
NAN_METHOD(GitTree::Lookup) {
  NanScope();
              if (args.Length() == 0 || !args[0]->IsObject()) {
      return NanThrowError("Repository repo is required.");
    }
                if (args.Length() == 1 || !args[1]->IsObject()) {
      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;
                      git_repository * from_repo;
          from_repo = ObjectWrap::Unwrap<GitRepository>(args[0]->ToObject())->GetValue();
  
            baton->repo = from_repo;
                                  const git_oid * from_id;
          from_id = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue();
  
            baton->id = from_id;
                    
  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 GitTree::LookupWorker::Execute() {
    int result = git_tree_lookup(
                    &baton->out,    
              baton->repo,    
              baton->id    
        );

    baton->error_code = result;

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

  }

void GitTree::LookupWorker::HandleOKCallback() {
  TryCatch try_catch;
  if (baton->error_code == GIT_OK) {
        Handle<Value> to;
                      if (baton->out != NULL) {
  to = GitTree::New((void *)baton->out);
} else {
  to = NanNull();
}
                        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(GitTree::Entrycount) {
  NanScope();
    
  
        
  size_t result = git_tree_entrycount(
          ObjectWrap::Unwrap<GitTree>(args.This())->GetValue()
            );

  

  Handle<Value> to;
          to = NanNew<Uint32>((uint32_t)result);
            NanReturnValue(to);
  }
                  /**
              * @param String filename
            * @return TreeEntry result  */
NAN_METHOD(GitTree::EntryByname) {
  NanScope();
              if (args.Length() == 0 || !args[0]->IsString()) {
      return NanThrowError("String filename is required.");
    }
      
  
                            const char * from_filename;
          String::Utf8Value filename(args[0]->ToString());
      from_filename = (const char *) strdup(*filename);
  
              
  const git_tree_entry * result = git_tree_entry_byname(
          ObjectWrap::Unwrap<GitTree>(args.This())->GetValue()
        ,          from_filename
            );

          free((void *)from_filename);
      

  Handle<Value> to;
          if (result != NULL) {
  to = GitTreeEntry::New((void *)result);
} else {
  to = NanNull();
}
          NanReturnValue(to);
  }
                  /**
              * @param Number idx
            * @return TreeEntry result  */
NAN_METHOD(GitTree::EntryByindex) {
  NanScope();
              if (args.Length() == 0 || !args[0]->IsUint32()) {
      return NanThrowError("Number idx is required.");
    }
      
  
                            size_t from_idx;
          from_idx = (size_t)   args[0]->ToUint32()->Value();
  
              
  const git_tree_entry * result = git_tree_entry_byindex(
          ObjectWrap::Unwrap<GitTree>(args.This())->GetValue()
        ,          from_idx
            );

    

  Handle<Value> to;
          if (result != NULL) {
  to = GitTreeEntry::New((void *)result);
} else {
  to = NanNull();
}
          NanReturnValue(to);
  }
                  /**
                * @param String path
            * @param TreeEntry callback
  */
NAN_METHOD(GitTree::EntryBypath) {
  NanScope();
                if (args.Length() == 0 || !args[0]->IsString()) {
      return NanThrowError("String path is required.");
    }
      
  if (args.Length() == 1 || !args[1]->IsFunction()) {
    return NanThrowError("Callback is required and must be a Function.");
  }

  EntryBypathBaton* baton = new EntryBypathBaton;
  baton->error_code = GIT_OK;
  baton->error = NULL;
                    baton->root = ObjectWrap::Unwrap<GitTree>(args.This())->GetValue();
                          const char * from_path;
          String::Utf8Value path(args[0]->ToString());
      from_path = (const char *) strdup(*path);
  
            baton->path = from_path;
                    
  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[1]));
  EntryBypathWorker *worker = new EntryBypathWorker(baton, callback);
                    worker->SaveToPersistent("root", args.This());
                        if (!args[0]->IsUndefined() && !args[0]->IsNull())
    worker->SaveToPersistent("path", args[0]->ToObject());
            
  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitTree::EntryBypathWorker::Execute() {
    int result = git_tree_entry_bypath(
                    &baton->out,    
              baton->root,    
              baton->path    
        );

    baton->error_code = result;

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

  }

void GitTree::EntryBypathWorker::HandleOKCallback() {
  TryCatch try_catch;
  if (baton->error_code == GIT_OK) {
        Handle<Value> to;
                      if (baton->out != NULL) {
  to = GitTreeEntry::New((void *)baton->out);
} else {
  to = NanNull();
}
                        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;
}
      

Persistent<Function> GitTree::constructor_template;
