// Very simple client that just sends
// lines to the server and reads lines
// that the server sends.
// $ java TCP_Client [server name]
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.io.*;

public class Lector {
  public static void main(String[] args) throws IOException, InterruptedException {
    // Passing null to getByName() produces the
    // special "Local Loopback" IP address, for
    // testing on one machine w/o a network:
    InetAddress addr =  InetAddress.getByName(args[0]);
    final int PORT = Integer.parseInt(args[1]);
    final long delta = Integer.parseInt(args[2]);
    // Alternatively, you can use 
    // the address or name:
    // InetAddress addr = InetAddress.getByName("127.0.0.1");
    // InetAddress addr = InetAddress.getByName("localhost");
    System.out.println("addr = " + addr);
    Socket socket = new Socket(addr, PORT);
    // Guard everything in a try-finally to make
    // sure that the socket is closed:
    try {
      System.out.println("socket = " + socket);
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      // Output is automatically flushed
      // by PrintWriter:
      PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
      ArrayList<Float> values_list = new ArrayList<Float>();
      ArrayList<Long> time_list = new ArrayList<Long>();;

      Runtime runTime= Runtime.getRuntime();
      Process process = runTime.exec("gnuplot");
      PrintWriter gnu_out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);
      gnu_out.println("set terminal x11");

      int it=0;
      while(true){
        
        // Esperar delta segundos y luego enviar caracter n
        Thread.sleep(delta*1000);
        out.println("n");
  
        // Se lee valor recibido y se guarda en arreglo
        String str = in.readLine();
        //System.out.println(str);
        

        if(it < 20){
          values_list.add(Float.parseFloat(str));
          time_list.add(Long.valueOf(it*delta));
          
        }
        else{
          Collections.rotate(values_list, -1);
          Collections.rotate(time_list, -1);
          values_list.set(19, Float.parseFloat(str));
          time_list.set(19,Long.valueOf(it*delta));
        }
        //System.out.println("time_list" + time_list.toString());
        
        it += 1;

        gnu_out.println("plot '-' using 1:2 with lines title 'medicion' ");
        
        for (int i = 0; i < time_list.size(); i++) {
          String timeString = String.valueOf(time_list.get(i));
          String valueString = String.valueOf(values_list.get(i));
          gnu_out.println(timeString + " " + valueString);
        }
        gnu_out.println("e");
      }
      //out.println("BYE");
    } finally {
      System.out.println("closing...");
      socket.close();
    }
  }
}
