package com.orbekk.stats;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import com.orbekk.stats.Experiments.Empty;
import com.orbekk.stats.Experiments.Experiment2;
import com.orbekk.stats.Experiments.SimpleTiming;

public class Experiment2Impl extends Experiment2 {
    private final static Logger logger = Logger.getLogger(Experiment2Impl.class.getName());
    // private List<SimpleTiming> samples = new ArrayList<SimpleTiming>();
    
    private HashMap<Integer, List<Double>> samples =
            new HashMap<Integer, List<Double>>();
    
    @Override
    public synchronized void registerSample(RpcController controller, SimpleTiming request,
            RpcCallback<Empty> done) {
        logger.info(request.toString());
        if (samples.get(request.getNumDevices()) == null) {
            samples.put(request.getNumDevices(), new ArrayList<Double>());
        }
        samples.get(request.getNumDevices()).add(request.getTiming());
        done.run(Empty.getDefaultInstance());
    }
    
    public void writeSamples(String filename) {
        PrintWriter printer = null;
        try {
            printer = new PrintWriter(filename);
            System.out.println("Writing results to " + filename);
            printer.println("# Automatically generated by Experiment2Impl.java");
            
            printer.println("# <numDevices> <avg latency> <avg-stddev> <avg+stddev>");
            for (int numDevices : samples.keySet()) {
                Analysis data = new Analysis(samples.get(numDevices));
                double avg = data.getAverage();
                double stddev = data.getStandardDeviation();
                printer.println(String.format(
                        "%d %f %f %f", numDevices, avg, avg-stddev, avg+stddev));
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (printer != null) {
                printer.close();
            }
        }
    }
}

Add Experiment2 server.