package sivantoledo.nxt.ping;

import org.eclipse.swt.widgets.Display;

import sivantoledo.nxt.Log;
import sivantoledo.nxt.NXTender;
import sivantoledo.nxt.Sender;
import sivantoledo.nxt.NXTender.Plugin;

public class Ping extends NXTender.Plugin {
  
  private Sender sender;
  
  private Ping(Sender sender) {
    super("PING");
    this.sender = sender;
  }
  
  public void close() {
  }

  private int  received;
  private double bytes;
  private double start_time;
  private double end_time;
  
  public void process(String command) {
    String[] terms = command.split(" ");

    if (terms.length > 1 && terms[1].equals("START")) {
      Log.println("PING START");
      received = 0;
      bytes    = 0;
      start_time = System.currentTimeMillis();
      Log.println("START AT "+start_time);
    } else if (terms.length > 1 && terms[1].equals("ONCE")) {
        Log.println("PING ONCE");
        received++;
        bytes += command.length();
        sender.send((byte) 1, "PONG");
    } else if (terms.length > 1 && terms[1].equals("MANY")) {
      Log.println("PING MANY");
      int howmany = Integer.parseInt(terms[2]);
      for (int i=0; i<howmany; i++)
        sender.send((byte) 1, "PONG");
    } else if (terms.length > 1 && terms[1].equals("MANYFAST")) {
      Log.println("PING MANYFAST");
      int howmany = Integer.parseInt(terms[2]);
      for (int i=0; i<howmany; i++)
        sender.send((byte) 1, "PONG", false);
    } else if (terms.length > 1 && terms[1].equals("END")) {
      end_time = System.currentTimeMillis();
      Log.println("PING END");
      int sent = Integer.parseInt(terms[2]);
      int dropped = sent - received;
      Log.println("END AT "+end_time);
      Log.println("PING Results:");    
      Log.println(received+" messages received");
      Log.println(dropped+" messages dropped");
      Log.println(bytes+" bytes total");
      Log.println((end_time - start_time)+" millisecond total");
      Log.println(((end_time - start_time)/received)+" millisecond per message");
      Log.printf("%.2e KB/s\n",(bytes/1024.0) / ((end_time-start_time)/1000.0));  
    } else {
      received++;
      bytes += command.length();
    }
  }

  private static Ping instance;  
  public static Ping getInstance(Sender sender) {
    if (instance == null) instance = new Ping(sender);
    return instance;
  }
  
}
