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

#include "../include/cred.h"

#include <iostream>

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

GitCred::GitCred(git_cred *raw, bool selfFreeing)
{
  this->raw = raw;
  this->selfFreeing = selfFreeing;
}

GitCred::~GitCred()
{
}

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

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

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

  NODE_SET_METHOD(tpl, "defaultNew", DefaultNew);
  NODE_SET_PROTOTYPE_METHOD(tpl, "hasUsername", HasUsername);
  NODE_SET_METHOD(tpl, "sshKeyFromAgent", SshKeyFromAgent);
  NODE_SET_METHOD(tpl, "sshKeyNew", SshKeyNew);
  NODE_SET_METHOD(tpl, "userpassPlaintextNew", UserpassPlaintextNew);

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

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

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

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

  NanReturnValue(args.This());
}

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

git_cred *GitCred::GetValue()
{
  return this->raw;
}

git_cred **GitCred::GetRefValue()
{
  return &this->raw;
}


/*
   * @param Cred callback
   */
NAN_METHOD(GitCred::DefaultNew)
{
  NanScope();

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

  DefaultNewBaton* baton = new DefaultNewBaton;

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


  NanCallback *callback = new NanCallback(Local<Function>::Cast(args[0]));
  DefaultNewWorker *worker = new DefaultNewWorker(baton, callback);

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitCred::DefaultNewWorker::Execute()
{
  int result = git_cred_default_new(
                 &baton->out    );

  baton->error_code = result;

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

}

void GitCred::DefaultNewWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

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

/*
     * @return Number  result    */
NAN_METHOD(GitCred::HasUsername)
{
  NanEscapableScope();

  int result = git_cred_has_username(
                 ObjectWrap::Unwrap<GitCred>(args.This())->GetValue()
               );

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

/*
  * @param String username
     * @return Cred out    */
NAN_METHOD(GitCred::SshKeyFromAgent)
{
  NanEscapableScope();

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

  git_cred * out = 0;
// start convert_from_v8 block
  const char * from_username;

  String::Utf8Value username(args[0]->ToString());
  from_username = (const char *) strdup(*username);
// end convert_from_v8 block
  int result = git_cred_ssh_key_from_agent(
                 &out
                 ,from_username
               );
  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) {
    // GitCred out
    to = GitCred::New((void *)out, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
  * @param String username
   * @param String publickey
   * @param String privatekey
   * @param String passphrase
     * @return Cred out    */
NAN_METHOD(GitCred::SshKeyNew)
{
  NanEscapableScope();

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

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

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

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

  git_cred * out = 0;
// start convert_from_v8 block
  const char * from_username;

  String::Utf8Value username(args[0]->ToString());
  from_username = (const char *) strdup(*username);
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_publickey;

  String::Utf8Value publickey(args[1]->ToString());
  from_publickey = (const char *) strdup(*publickey);
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_privatekey;

  String::Utf8Value privatekey(args[2]->ToString());
  from_privatekey = (const char *) strdup(*privatekey);
// end convert_from_v8 block
// start convert_from_v8 block
  const char * from_passphrase;

  String::Utf8Value passphrase(args[3]->ToString());
  from_passphrase = (const char *) strdup(*passphrase);
// end convert_from_v8 block
  int result = git_cred_ssh_key_new(
                 &out
                 ,from_username
                 ,from_publickey
                 ,from_privatekey
                 ,from_passphrase
               );
  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) {
    // GitCred out
    to = GitCred::New((void *)out, false);
  } else {
    to = NanNull();
  }

// end convert_to_v8 block
  NodeGitPsueodoNanReturnEscapingValue(to);
}

/*
  * @param String username
   * @param String password
    * @param Cred callback
   */
NAN_METHOD(GitCred::UserpassPlaintextNew)
{
  NanScope();

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

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

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

  UserpassPlaintextNewBaton* baton = new UserpassPlaintextNewBaton;

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

// start convert_from_v8 block
  const char * from_username;

  String::Utf8Value username(args[0]->ToString());
  from_username = (const char *) strdup(*username);
// end convert_from_v8 block
  baton->username = from_username;
// start convert_from_v8 block
  const char * from_password;

  String::Utf8Value password(args[1]->ToString());
  from_password = (const char *) strdup(*password);
// end convert_from_v8 block
  baton->password = from_password;

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

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

void GitCred::UserpassPlaintextNewWorker::Execute()
{
  int result = git_cred_userpass_plaintext_new(
                 &baton->out,baton->username,baton->password    );

  baton->error_code = result;

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

}

void GitCred::UserpassPlaintextNewWorker::HandleOKCallback()
{
  TryCatch try_catch;

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

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

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