#include "key_keeper.h"
#include "tfe_future.h"
#include "ssl_utils.h"
#include "tfe_rpc.h"


void ask_key_keeper_on_succ(void* result, void* user);

void ask_key_keeper_on_fail(enum e_future_error error, const char * what, void * user);

struct key_keeper_ctx{
	struct key_keeper* keeper;
	struct future* f;
};

int main()
{
	void* logger = NULL;
	future_promise_library_init(NULL);
	//struct event_base* evbase = event_base_new();
	struct key_keeper * keeper = key_keeper_init("./conf/tfe.conf", "key_keeper", logger);
	struct key_keeper_ctx* ctx = (struct key_keeper_ctx*)malloc(sizeof(struct key_keeper_ctx));
	ctx->keeper = keeper;
	struct future* f = future_create("key_keeper", ask_key_keeper_on_succ, ask_key_keeper_on_fail, ctx);
	ctx->f = f;
	X509* origin_cert = ssl_x509_load("./conf/origin_cert.pem");
	printf("-------------------------------\n");
	int i = 0;
	printf("call key_keeper_async_ask, i = %d\n", i);
	key_keeper_async_ask(f, keeper, "www.baidu.com", 1, origin_cert, 1, NULL, NULL);
	X509_free(origin_cert);
	key_keeper_destroy(keeper);
	future_destroy(f);
	free(ctx);
	//event_base_dispatch(evbase);
	/*
	struct event_base* evbase1 = event_base_new();
	struct future* f1 = future_create("key_keeper", ask_key_keeper_on_succ, ask_key_keeper_on_fail, user);
	key_keeper_async_ask(f1, keeper, "www.baidu.com", 0, origin_cert, 0, evbase1);
	event_base_dispatch(evbase1);
	*/
}

void ask_key_keeper_on_succ(void* result, void* user)
{
	//printf("call ask_key_keeper_on_succ\n");
	struct keyring* kyr = key_keeper_release_keyring(result);
	X509* cert = kyr->cert;
	EVP_PKEY* key = kyr->key;
	STACK_OF(X509) * chain = kyr->chain;
	if(cert)
	{
		printf("cert is not null\n");
	}
	if(key)
	{
		printf("key is not null\n");
	}
	if(chain)
	{
		printf("chain is not null\n");
	}
	key_keeper_free_keyring(kyr);
	return;
}

void ask_key_keeper_on_fail(enum e_future_error error, const char * what, void * user)
{
	printf("call ask_key_keeper_on_fail\n");
	printf("what is %s\n", what);
}
