/*
 *$Log$
 */
package network;
import java.util.*;
import java.awt.*;

import general.*;
import gui.*;
import network.*;

public class CalcLinkDimension extends Thread {
  GeneralProperties gpData;
  String constraints;
  Vector objectives;
  public CalcLinkDimension(Vector objectives, String constraints,
			   GeneralProperties gpData) {
    this.gpData = gpData;
    this.constraints = constraints;
    this.objectives = objectives;
  }

  public void run() {
    int retry;
    Network n = (Network)gpData.get("Network");
    n.cost = 0;
    dLinkCosts dlc = 
      (dLinkCosts)gpData.get("dLinkCosts");
    dlc.update();
    dlc.setRunning();
    dlc.disableUpdateButton();
    dlc.show();
    Link curLink;
    String rdata;
    double capL2R = 0, capR2L = 0;
    double cost = 0;
    Hashtable hLinks = n.getLinksToDimension();
    Enumeration e = hLinks.elements();
    int count = 0;
    while (e.hasMoreElements()) {
      curLink = (Link)e.nextElement();
      retry = 0;
      do {
	rdata
	  = CGI.linearProgramming( (String)objectives.elementAt(count) + constraints );
	capL2R = LP.parseObjectiveValue(rdata);
	++retry;
      }
      while (capL2R == -1 && retry < 20);
      if (capL2R < 0) {
	reportError();
	return;
      }
      curLink.setL2R(capL2R);
      ++count;

      //      System.out.println(objectives.elementAt(2*i+1));
      if (n.getLinkDirection().equals(dSelectLinks.TWO_DIRECTION)) {
	retry = 0;
	do {
	  rdata
	    = CGI.linearProgramming( (String)objectives.elementAt(count) + constraints );
	  capR2L = LP.parseObjectiveValue(rdata);
	  ++retry;
	}
	while (capR2L == -1 && retry < 20);
	if (capR2L < 0) {
	  reportError();
	  return;
	}
	++count;
      }
      curLink.setR2L(capR2L);
	
      dlc.updateItem(curLink);
      cost += (capL2R + capR2L)*curLink.getLength();
    }
    n.cost = cost;
    dlc.enableUpdateButton();
    dlc.update();
    GUICanvas c = (GUICanvas)gpData.get("Canvas");
    c.repaint();
  }

  private void reportError() {
    Network n = (Network)gpData.get("Network");
    n.cost = 0;
    dLinkCosts dlc = 
      (dLinkCosts)gpData.get("dLinkCosts");
    dlc.enableUpdateButton();
    dlc.update();
    GUICanvas c = (GUICanvas)gpData.get("Canvas");
    c.repaint();
    GUIManager guimng = (GUIManager)gpData.get("GUIManager");
    guimng.DisplayMessageBox("Error Dimensioning Links", 
			     "can not dimension link due to network error!");   
  }
    
} // end of class



