package com.ibm.dynademo;

import proxy.soap.*;
import mappings.*;

/**
 * <code>TemperatureLister</code> lists temperature readings. It uses three Web Services:
 *
 * 1. ZipCode Service lists zip codes and cities.
 * 2. Temperature Service gives the Fahrenheit temperature at a zip code.
 *    TestTemperatureService is a local version for use when disconnected.
 * 3. TemperatureConverter Service converts from Fahrenheit to Celsius.
 * 
 * @author Arthur Ryman
 * @version 1.0
 */
public class TemperatureLister {

	/** use the TestTemperatureService when local is true */
	private boolean local;
	public void setLocal(boolean local) {
		this.local = local;
	}
	public boolean isLocal() {
		return local;
	}

	/**
	 * Lists the temperature readings for a city.
	 * 
	 * @return the temperature listing
	 * @param city the string city name
	 */
	public TemperatureListing forCity(String city) {

		// get the array of zip codes
		try {

			ZipCodeProxy proxy = new ZipCodeProxy();
			TemperatureServiceProxy temperatureProxy = new TemperatureServiceProxy();
			TestTemperatureServiceProxy testProxy = new TestTemperatureServiceProxy();
			TemperatureConverterProxy converterProxy = new TemperatureConverterProxy();

			FindZipCodesResult_ElementContentType result = proxy.findZipCodes(city);
			FindZipCodesResult_ElementContentType
				.FindZipCodesRow_ElementLocalContentType[] rows =
				result.getFindZipCodesRow();

			TemperatureReading[] readings = new TemperatureReading[rows.length];
			for (int i = 0; i < readings.length; i++) {

				String zipCode = rows[i].getZIPCODE();

				// get the temperature
				float fahrenheit =
					isLocal() ? testProxy.getTemp(zipCode) : temperatureProxy.getTemp(zipCode);

				// convert the temperature
				float celsius = converterProxy.convertFtoC(fahrenheit);

				// round to one decimal place
				celsius = (float) (Math.round(celsius * 10) * 0.1);

				TemperatureReading reading = readings[i] = new TemperatureReading();
				reading.setCity(city);
				reading.setZipCode(zipCode);
				reading.setFahrenheit(fahrenheit);
				reading.setCelsius(celsius);
			}

			return new TemperatureListing(readings);

		} catch (Exception e) {

			return new TemperatureListing(e.getMessage());
		}
	}
}