import popcorn.*;
import java.awt.*;
import java.applet.Applet;
import simulatedAnnealing.*;
import popcorn.buyer.*;

/** A demo applet for the tsp using simulated annealing*/
public class TravelingSalesmanDemoApplet extends Applet implements Runnable,
                                                                   ComputationObserver {

  WorldMap map = new WorldMap();
  Label statusLabel = new Label();
  TextArea window;
  City[] cities;
  int[] bestOrder;
  Res res;
  boolean FirstFlag;

  private static final double KM_PER_PIXEL = 47.0;

  public void init() {
    setLayout(new PropertiesLayout());
    Font titleFont = new Font(getFont().getName(),12,Font.PLAIN);
    Label titleLabel = new Label("Traveling Salesman Problem");
    titleLabel.setFont(titleFont);
    add("name=l1,x=0.5,top=$20",titleLabel);
    add("name=map,x=0.5,top=l1.bottom,q=$15,width=$851,height=$527",map);
    window=new TextArea();
    add("name=window,x=0.5,top=map.bottom,q=$10,width=map.width,height=$90",window);
    Font statusFont = new Font(getFont().getName(),10,Font.PLAIN);
    statusLabel.setFont(statusFont);
    add("name=status,x=0.5,top=window.bottom,q=$15,width=map.width",statusLabel);

    cities = map.getCities();
    new Thread(this).start();
  }


  public void run() {
    repaint();
    execute(cities);
    System.err.println("The minimal distance is:"+((float)((int)(KM_PER_PIXEL*res.path.length*100))/100));
    System.err.println("done");
  }

  private void execute(City[] cities) {
    SimulatedAnnealingComputation computation = new SimulatedAnnealingComputation(cities,this);
    computation.go();
    Computation.collectAll();
    res = computation.result();
    updateDisplay(res.path.order);
    updateStatus(res.path.length,res.packetsSent,res.packetsArrived);
  }

  public void updateDisplay(Object state) {
    bestOrder = (int[])state;
    map.setPath(bestOrder);
    map.drawingPathOn();
    map.repaint();
    printList(bestOrder);
  }


  public void updateStatus(double min,int packetsSent,int packetsArrived) {
    String minString = "Minimal distance: "+((float)((int)(KM_PER_PIXEL*min*100))/100)+"km";
    String status = minString+"  Packet sent: "+packetsSent+"  Packet arrived: "+packetsArrived;;
    statusLabel.setText(status);
  }

  void printList(int[] path) {
    String line="";
    int n=cities.length;
    for (int i=0; i<n; i++) {
      line+= cities[path[i]].getName()+"-->";
      if (i%8==7)
        line+="\n";
    }
    line+=cities[path[0]].getName()+"\n";
    window.setText(line);
  }
}



