// RPC stubs for clients to talk to lock_server

#include "lock_client.h"
#include "rpc.h"
//#include <stdlib.h>

 int acq_nonce; 
 int rel_nonce;
 pthread_mutex_t acq_lock, rel_lock;

lock_client::lock_client(sockaddr_in xdst)
  : dst(xdst)
{
  assert(pthread_mutex_init(&acq_lock, NULL) == 0);
  assert(pthread_mutex_init(&rel_lock, NULL) == 0);
  id = random();
  printf("the id of this client is %d \n", id);
  acq_nonce = 0;
  rel_nonce = 0;
}

int
lock_client::stat(std::string name)
{
  int r;
  int ret = cl.call(dst, lock_protocol::stat, name, r);
  assert (ret == lock_protocol::OK);
  return r;
}

lock_protocol::status
lock_client::acquire(std::string name)
{	
	pthread_mutex_lock(&acq_lock);
	acq_nonce++;
	int r = acq_nonce;
	pthread_mutex_unlock(&acq_lock);
	//printf("acquire, sending nonce: %d \n", acq_nonce);
	int ret = cl.call(dst, lock_protocol::acquire, name, r, getpid(), r);
	return ret;	
}

lock_protocol::status
lock_client::release(std::string name)
{	 
	pthread_mutex_lock(&rel_lock);
	rel_nonce++;
	int r = rel_nonce;
	pthread_mutex_unlock(&rel_lock);
	int ret = cl.call(dst, lock_protocol::release, name, r, getpid(), r);
	return ret;	
}

