
/**
 * Carta.java
 *
 * a map for searching
 * called Carta to avoid confusion with Interface map
 * Created: Mon Dec  4 16:45:12 2000
 *
 * @author <a href="mailto: "Phil Green</a>
 * @version
 */

import sheffield.*;
import java.util.*;

public class Carta{
  private ArrayList links; // all the links
  private HashSet cities;  // all the cities
  
  //accessors
  public ArrayList getAllLinks() {return links;}
  public HashSet getCities() {return cities;}

  //constructor - empty map
  
  public Carta(){
  links = new ArrayList();
  }
  
  /**
  * add_Link adds a link to a map
  * @param c1 city 1
  * @param c2 city 2
  * @param c cost of the link
  */
  public void add_Link(String c1, String c2, int c){
    Maplink ml=new Maplink(c1,c2,c);
    links.add(ml);
  }
  
  public String toString(){
    StringBuffer buf = new StringBuffer("MAP WITH LINKS\n");
    for (Iterator l = links.iterator(); l.hasNext();){
      Maplink lnk = (Maplink) l.next();
      String lstr = lnk.toString();
      buf.append(lstr+"\n");
    }
    return buf.toString();
  }
  
  /**
  * get_Links
  * returns all links to/from a given city
  * @param city - the city
  * @return ArrayList of links 
  */
  public ArrayList get_Links(String city){
    ArrayList clinks = new ArrayList();
     for (Iterator li = links.iterator(); li.hasNext();){
       Maplink l= (Maplink) li.next();
       if ((city.compareTo(l.get_city1())==0)||(city.compareTo(l.get_city2())==0))
         clinks.add(l);
     }
     return clinks;
  }
  
  /**
  * costbetween
  * returns cost between 2 cities
  * @param c1 city 1
  * @param c2 city 2
  */
  
  public int costbetween(String c1,String c2){
    ArrayList c1links=get_Links(c1);
    int ans=-1;
    Iterator i =c1links.iterator();
    while (i.hasNext()&&(ans<0)){
      Maplink l= (Maplink) i.next();
      if (c2.equals(l.get_city1()) || c2.equals(l.get_city2())){
        ans= l.get_cost();
      }
    }
    return ans;
  }
         

  /**
  * mapFromFile
  * reads a map from file
  * @param fname - the file name
  */
    
  public void  mapFromFile(String fname){
    EasyReader rdr = new EasyReader(fname);
    String c1 = rdr.readString();
    while (c1.compareTo("done")!=0){
      links.add(new Maplink(c1, rdr.readString(), rdr.readInt()));
      c1 = rdr.readString();
      }
    findcities(); // uses the links to find the cities
  }
  
  // find all cities on the map
  
  private void findcities(){
    cities= new HashSet();
    for (Iterator i=links.iterator(); i.hasNext();){
      Maplink l= (Maplink) i.next();
      cities.add(l.get_city1());
      cities.add(l.get_city2());
    }
  }
}  
	
      
  

	 
				 
    

  
