import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

public class Weather extends Applet {
  protected String initialCity = "Los Angeles";
  private CityChooser cityChooser;
  private Button forecastButton;
  private WeatherPanel weatherPanel;

  public void init() {
    Panel topPanel = new Panel();
    topPanel.add(new Label("City:"));
    cityChooser = new CityChooser(initialCity);
    topPanel.add(cityChooser);
    forecastButton = new Button("Get Forecast");
    topPanel.add(forecastButton);
    setLayout(new BorderLayout());
    add("North", topPanel);
    weatherPanel =
      new WeatherPanel(initialCity,
                       getWeather(initialCity),
                       this);
    add("Center", weatherPanel);
  }

  public boolean action(Event e, Object o) {
    if (e.target == forecastButton) {
      String city = cityChooser.getCity();
      weatherPanel.setCity(city);
      weatherPanel.setWeather(getWeather(city));
      weatherPanel.repaint();
      return(true);
    } else
      return(false);
  }
  
  public String getWeather(String city) {
    String weather = "partly-cloudy";
    try {
      URL weatherInfo =
        new URL("http://www.apl.jhu.edu/" +
                "cgi-instruct/hall/WeatherInfo");
      URLConnection connection =
        weatherInfo.openConnection();
      connection.setDoOutput(true);
      PrintStream out =
        new PrintStream(connection.getOutputStream());
      out.println("city=" + URLEncoder.encode(city));
      out.close();
      DataInputStream in =
        new DataInputStream(connection.getInputStream());
      weather = in.readLine();
      in.close();
    } catch(MalformedURLException mue) {
      showStatus("Illegal URL: " + mue);
    } catch(IOException ioe) {
      showStatus("IOException: " + ioe);
    } catch(Exception e) {
      showStatus("Error: " + e);
    }
    return(weather);
  }
}
