#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include <unistd.h>
#include "gcache.h"

static int nServerPort;

int InitGlobalCache(int nPort)
    {
    nServerPort=nPort;
    }

static int OpenServer()
    {
    int nSocket;
    struct sockaddr_in saServer;

    nSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(nSocket < 0)
	{
	perror("socket");
	exit(2);
	}

    memset(&saServer,0,sizeof saServer);
    saServer.sin_family=AF_INET;
    saServer.sin_addr.s_addr=htonl(0x7f000001);
    saServer.sin_port=htons(nServerPort);
    if(connect(nSocket,(struct sockaddr *)&saServer,sizeof saServer))
       {
       perror("connect");
       assert(0);
       }
    return nSocket;
    }
    

static void WriteCommand(int nFD,enum Command eCommand)
    {
    static char c;

    c=eCommand;
    write(nFD,&c,1);
    }

void GlobalCacheAdd(uchar *aucKey,int nKey,uchar *aucData,
		int nData,time_t tExpiresAt)
    {
    int nFD=OpenServer();

    WriteCommand(nFD,ADD_TO_CACHE);
    WriteThing(nFD,aucKey,nKey);
    WriteThing(nFD,aucData,nData);
    write(nFD,&tExpiresAt,sizeof tExpiresAt);
    close(nFD);
    }

uchar *GlobalCacheGet(uchar *aucKey,int nKey,int *pnData,time_t *ptExpiresAt)
    {
    int nFD=OpenServer();
    uchar *ret;

    WriteCommand(nFD,GET_FROM_CACHE);
    WriteThing(nFD,aucKey,nKey);
    ret=ReadThing(nFD,pnData);
    if(ret)
	read(nFD,ptExpiresAt,sizeof *ptExpiresAt);
    close(nFD);
    return ret;
    }
