package anastore.test;

import anastore.client.*;
import anastore.net.*;
import anastore.util.*;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Single-client test: create a block, and repeatedly read and
 * increment its value, checking that the value is correct.
 */
public class IncrementSingleClient {

    public static final void main(final String[] args) {
        try {
            if (args.length != 3) {
                System.err.println("usage: <hostname> <port> <cache-dir>");
                System.exit(1);
            }

            ChannelClient client =
                new ChannelClient(args[0],
                                  Integer.parseInt(args[1]));
            Pair<SendChannel, ReceiveChannel> channels = client.connect();
            SendChannel send = channels.first;
            ReceiveChannel recv = channels.second;
            File cache = new File(args[2]);
            BlockStore store = BlockStore.connect(send, cache);


            // Create a block
            Pair<Long, ByteBuffer> block;
            try {
                RWSnapshot snap = store.beginRW();
                block = snap.newBlock(8);
                block.second.putLong(0,0);
                snap.commit();
            } catch (AbortedException e) {
                throw new RuntimeException(e);
            }
            
            for (long i = 1; i < 25; i++) {
                try {
                    RWSnapshot snap = store.beginRW();
                    ByteBuffer rBuf = snap.readBlock(block.first);
                    long value = rBuf.getLong(0);
                    System.out.println("Read: got " + value);
                    assert(i == value+1);

                    ByteBuffer wBuf = snap.readWriteBlock(block.first);
                    wBuf.putLong(0,i);
                    snap.commit();                    
                } catch (AbortedException e) {
                    throw new RuntimeException(e);
                }
            }

            System.out.println("Success!");
            System.exit(0);
            
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
