/*
 * $Log$
 */

package gui;

// Standard packages.
import java.applet.Applet;
import java.awt.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;

import network.*;
import general.*;

public class dOptimizeDistributedRoute extends GridBagDialog {
  private TextField tfNumber = new TextField("3", 5);
  private TextField tfRatio = new TextField("2.0", 5);
  private TextField tfWeights = new TextField("2 1 1", 30);
  private Button bOk = new Button("OK");
  private Frame parent;

  private int number;
  private float ratio;
  private float[] weights;
  private GeneralProperties gpData;

  //************************************************
  public dOptimizeDistributedRoute(Frame parent, GeneralProperties gp) {
    super(parent, "Distrubuted Route Parameters", true);
    this.parent = parent;
    gpData = gp;
    gbc.anchor = GridBagConstraints.WEST;
    add(new Label("maximum number of different routes to use"), 0, 0, 5, 1);
    add(tfNumber, 5, 0, 1, 1);
    add(new Label("longest route/shortest route"), 0, 1, 5, 1);
    add(tfRatio, 5, 1, 1, 1);
    add(new Label("relative weights of different routes"), 0, 2, 6, 1);
    add(tfWeights, 0, 3, 6, 1);
    gbc.anchor = GridBagConstraints.CENTER;
    add(bOk, 3, 4, 2, 1);
    pack();
  }

  public int getNRoute() {
    return number;
  }

  public float getRatio() {
    return ratio;
  }

  public float[] getWeights() {
    return weights;
  }

  public boolean checkInputs() {
    number = Integer.parseInt(tfNumber.getText());
    if (number < 1) return false;
    ratio = (new Float(tfRatio.getText())).floatValue();
    if (ratio < 1.0) return false;
    StringTokenizer stk = new StringTokenizer( tfWeights.getText(), " ,;\t\n\r");
    weights = new float[number];
    int index;
    for (index = 0; index < number; ++index)
      weights[index] = (float)1.0;
    index = 0;
    while (stk.hasMoreTokens() && index < number) {
      weights[index] = (new Float(stk.nextToken())).floatValue();
      if (weights[index] < 0) return false;
      ++index;
    }
    return true;
  }

  public boolean handleEvent(Event e) {
    if(e.id == Event.KEY_PRESS) { // to let components handle keyboard
				// events. (required due to bug in java). 
      return false;
    }
    else if(e.target == bOk && e.id == Event.ACTION_EVENT) {
      if ( checkInputs() ) {
	Network network = (Network)gpData.get("Network");
	DistributedRoute dstrt
	  = new DistributedRoute(network.switches, network.links, getWeights(),
				 getNRoute(), getRatio());
	dstrt.apply();
	dispose();
	return true;
      }
      else {
	// show alert
	return true;
      }
    }
    else {
      super.handleEvent(e);
    }
    return true;
  }
//************************************************
} // End of class dOptionScale
//////////////////////////////////////////////////
