/*
 * Excercise data cache functions.
 */
#include <stdio.h>
#include <stdlib.h>
#include "data_cache.h"

struct attributes {
    int state;
    int date;
    char vms_dev[16];
    char vms_fid[6];
};

int main(int argc, char **argv)
{
    int status, i, attr_len, length, count; char *rec;
    int chunk_stats[8], item_stats[8];
    void tcache_get_counters();
    char dummy[8000];
    struct tcache_context ctx;
    struct attributes *attr_ptr, my_attr;
    if ( argc < 3 ) { printf("Usage: test size, data_limit\n"); exit(1); }
    status = tcache_init ( atoi(argv[1]), atoi(argv[2]) );
    printf("status of tcache_init: %d\n", status );

    status = tcache_access ( 1, 
	"/demo/index.html", &ctx, (void **) &attr_ptr, &attr_len );
    printf("status of tcache_open for /demo/index.html: %d, %x %d\n",
		status, attr_ptr, attr_len );
    if ( status == TCACHE_ACCESS_CREATED ) {
	status = tcache_put ( &ctx, "<HTML><HEAD><TITLE>test</TITLE></HEAD>",
		38 );
	printf ( "Status of data put: %d\n", status );
	if ( argc > 3 ) {
	    count = atoi ( argv[3] );
	    if ( count > 800 ) count = 800;
	    for ( i = 1; i <= count; i++ ) {
		status = tcache_put ( &ctx, dummy, i*10 );
	    }
	}
	status = tcache_put ( &ctx, &my_attr, sizeof(my_attr) );
	printf ( "Status of attr put: %d\n", status );
    } else {
	printf("Unexpected status: %d\n", status);
	return 20;
    }
    status = tcache_deaccess ( &ctx, 0 );

    status = tcache_access ( 1, "/demo/index.html", &ctx,
		(void **) &attr_ptr, &attr_len );
    printf("status of 2nd tcache_open for /demo/index.html: %d, %x %d\n",
		status, attr_ptr, attr_len );
    if ( status == TCACHE_ACCESS_SUCCESS ) {
	do {
	    status = tcache_get ( &ctx, (void **) &rec, &length );
	    printf("tcache_get status: %d, %x length: %d\n", status, rec, length );
 	} while ( status == TCACHE_SUCCESS && rec != (char *) attr_ptr );
	status = tcache_get ( &ctx, (void *) &attr_ptr, &length );
	printf ( "Status of extra get: %d, %x, %d\n", status, attr_ptr, length );
    } else {
	printf("Unexpected status\n");
	return 20;
    }
    tcache_get_counters ( item_stats, chunk_stats, 0 );
    printf("Item stats:");
    for(i=0;i<8;i++) printf(" %d", item_stats[i] );
    printf("\nchunk stats:");
    for(i=0;i<8;i++) printf(" %d", chunk_stats[i] );
    printf("\n");
    return 1;
}
