/*
 * Compile this file together with the Vedis source code
 * to generate the executable. For example: 
 *  gcc -W -Wall -O6 vedis_kv_intro.c vedis.c -o vedis_kv
*/
/*
 * This simple program is a quick introduction on how to embed and start
 * experimenting with Vedis without having to do a lot of tedious
 * reading and configuration.
 *
 * Introduction to the Key/Value Store Interfaces:
 *
 * Vedis is a standard key/value store similar to BerkeleyDB, Tokyo Cabinet, LevelDB, etc.
 * But, with a rich feature set including support for transactions (ACID), concurrent reader, etc.
 * Under the KV store, both keys and values are treated as simple arrays of bytes, so content
 * can be anything from ASCII strings, binary blob and even disk files.
 * The KV store layer is presented to host applications via a set of interfaces, these includes:
 * vedis_kv_store(), vedis_kv_append(), vedis_kv_fetch_callback(), vedis_kv_append_fmt(),
 * vedis_kv_delete(), vedis_kv_fetch(), etc.
 *
 * For an introduction to the Vedis C/C++ interface, please refer to:
 *        http://vedis.symisc.net/api_intro.html
 * For the full C/C++ API reference guide, please refer to:
 *        http://vedis.symisc.net/c_api.html
 * Vedis in 5 Minutes or Less:
 *        http://vedis.symisc.net/intro.html
 * Built-in Vedis Commands:
 *        http://vedis.symisc.net/commands.html
 */
/* $SymiscID: vedis_kv_intro.c v1.0 Win7 2013-09-12 01:15 stable <chm@symisc.net> $ */
/* 
 * Make sure you have the latest release of Vedis from:
 *  http://vedis.symisc.net/downloads.html
 */
#include <stdio.h>  /* puts() */
#include <stdlib.h> /* exit() */
/* Make sure this header file is available.*/
#include "vedis.h"
/*
 * Banner.
 */
static const char zBanner[] = {
	"============================================================\n"
	"Vedis Key/Value Store Intro                                 \n"
	"                                    http://vedis.symisc.net/\n"
	"============================================================\n"
};
/*
 * Extract the datastore error log and exit.
 */
static void Fatal(vedis *pStore,const char *zMsg)
{
	if( pStore ){
		const char *zErr;
		int iLen = 0; /* Stupid cc warning */

		/* Extract the datastore error log */
		vedis_config(pStore,VEDIS_CONFIG_ERR_LOG,&zErr,&iLen);
		if( iLen > 0 ){
			/* Output the error log */
			puts(zErr); /* Always null termniated */
		}
	}else{
		if( zMsg ){
			puts(zMsg);
		}
	}
	/* Manually shutdown the library */
	vedis_lib_shutdown();
	/* Exit immediately */
	exit(0);
}
/* Forward declaration: Data consumer callback */
static int DataConsumerCallback(const void *pData,unsigned int nDatalen,void *pUserData /* Unused */);

int main(int argc,char *argv[])
{
	vedis *pStore;          /* Datastore handle */
	int i,rc;

	puts(zBanner);

	/* Open our datastore */
	rc = vedis_open(&pStore,argc > 1 ? argv[1] /* On-disk DB */ : ":mem:" /* In-mem DB */);
	if( rc != VEDIS_OK ){
		Fatal(0,"Out of memory");
	}
	
	/* Store some records */
	rc = vedis_kv_store(pStore,"test",-1,"Hello World",11); /* test => 'Hello World' */
	if( rc != VEDIS_OK ){
		/* Insertion fail, extract datastore error log and exit */
		Fatal(pStore,0);
	}
	/* A small formatted string */
	rc = vedis_kv_store_fmt(pStore,"date",-1,"dummy date: %d:%d:%d",2013,9,17); /* Dummy date */
	if( rc != VEDIS_OK ){
		/* Insertion fail, extract datastore error log and exit */
		Fatal(pStore,0);
	}
	
	/* Switch to the append interface */
	rc = vedis_kv_append(pStore,"msg",-1,"Hello, ",7); //msg => 'Hello, '
	if( rc == VEDIS_OK ){
		/* The second chunk */
		rc = vedis_kv_append(pStore,"msg",-1,"Current time is: ",17); /* msg => 'Hello, Current time is: '*/
		if( rc == VEDIS_OK ){
			/* The last formatted chunk */
			rc = vedis_kv_append_fmt(pStore,"msg",-1,"%d:%d:%d",10,12,42); /* msg => 'Hello, Current time is: 10:12:45' */
		}
	}
	/* Store 20 random records.*/
	for(i = 0 ; i < 20 ; ++i ){
		char zKey[12]; /* Random generated key */
		char zData[34]; /* Dummy data */
		
		/* Generate the random key */
		vedis_util_random_string(pStore,zKey,sizeof(zKey));
		
		/* Perform the insertion */
		rc = vedis_kv_store(pStore,zKey,sizeof(zKey),zData,sizeof(zData));
		if( rc != VEDIS_OK ){
			break;
		}
	}
	if( rc != VEDIS_OK ){
		/* Insertion fail, rollback the transaction  */
		rc = vedis_rollback(pStore);
		if( rc != VEDIS_OK ){
			/* Extract datastore error log and exit */
			Fatal(pStore,0);
		}
	}


	puts("Done...Fetching some records");

	/* Invoke the supplied callback for each retrieved record*/
	rc = vedis_kv_fetch_callback(pStore,"test",-1,DataConsumerCallback,0);
	if( rc != VEDIS_OK ){
		/* Can't happen */
		Fatal(pStore,0);
	}
	printf("\n");
	rc = vedis_kv_fetch_callback(pStore,"msg",-1,DataConsumerCallback,0);
	if( rc != VEDIS_OK ){
		/* Can't happen */
		Fatal(pStore,0);
	}
	
	/* Delete a record */
	vedis_kv_delete(pStore,"test",-1);
	
	/* Auto-commit the transaction and close our datastore */
	vedis_close(pStore);
	return 0;
}

#ifdef __WINNT__
#include <Windows.h>
#else
/* Assume UNIX */
#include <unistd.h>
#endif
/*
 * The following define is used by the UNIX build process and have
 * no particular meaning on windows.
 */
#ifndef STDOUT_FILENO
#define STDOUT_FILENO	1
#endif
/*
 * Data consumer callback [vedis_kv_fetch_callback(), vedis_kv_cursor_key_callback(), etc.).
 * 
 * Rather than allocating a static or dynamic buffer (Inefficient scenario for large data).
 * The caller simply need to supply a consumer callback which is responsible of consuming
 * the record data perhaps redirecting it (i.e. Record data) to its standard output (STDOUT),
 * disk file, connected peer and so forth.
 * Depending on how large the extracted data, the callback may be invoked more than once.
 */
static int DataConsumerCallback(const void *pData,unsigned int nDatalen,void *pUserData /* Unused */)
{
#ifdef __WINNT__
	BOOL rc;
	rc = WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),pData,(DWORD)nDatalen,0,0);
	if( !rc ){
		/* Abort processing */
		return VEDIS_ABORT;
	}
#else
	ssize_t nWr;
	nWr = write(STDOUT_FILENO,pData,nDatalen);
	if( nWr < 0 ){
		/* Abort processing */
		return VEDIS_ABORT;
	}
#endif /* __WINT__ */
	
	/* All done, data was redirected to STDOUT */
	return VEDIS_OK;
}