package edu.brynmawr.ple2;

import android.util.Log;

import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.SphericalUtil;


public class City implements Comparable<City>
{
	public enum SortBy { name, distance };
	public static SortBy sortBy = SortBy.name;

	public final int position;
	public final String name;
	public final String state;
	public final String population;
	public final String percentage;
	public final String region;
	public final String country;
	private float longitude;
	private float latitude;
	private int lCount=0;
	private LatLng latlng;

	private double distance=0;

	public void addLongLat(float longitude, float latitude) {
		this.longitude += longitude;
		this.latitude += latitude;
		this.lCount++;
	}

	public boolean normalizeLongitudeLatitude() {
		if (lCount==0) {
			this.latlng = new LatLng(-1,-1);
			Log.e("THISS", "No LongLat for " + name + " " + state);
			return false;
		}
		this.longitude /= lCount;
		this.latitude /= lCount;
		this.latlng = new LatLng(this.latitude, this.longitude);
		longitude=0;
		latitude=0;
		lCount=0;
		return true;
	}
	public double getLatitude() {
		return latlng.latitude;
	}
	public double getLongitude() {
		return latlng.longitude;
	}

	private double distanceBetween(LatLng point1, LatLng point2) {
		if (point1 == null || point2 == null) {
			return -1;
		}
		return SphericalUtil.computeDistanceBetween(point1, point2);
	}

	public void setDistanceFrom(LatLng frompt) {
		this.distance = distanceBetween(latlng, frompt);
	}
	public double getDistance() {
		return this.distance;
	}


	public City(String cString) throws ArrayIndexOutOfBoundsException
	{
		String[] aa = cString.split(",");
		int tmpPos = 114; // default is Aurora, Illinois (go Waynes World!)
		try
		{
			tmpPos = Integer.parseInt(aa[0]);
		} catch (Exception ee) {
			Log.e("THISS", "Problem parsing to int " + aa[0]);
		}
		this.position = tmpPos;
		this.name = aa[1];
		this.state = aa[2];
		this.population = aa[3];
		this.percentage = aa[4];
		this.region = DataCities.state2Region(this.state);
		this.country = "USA";
	}

	public boolean equals(String cityName, String stateName)
	{
		return this.name.equals(cityName) &&
				this.state.equals(stateName);
	}

	@Override
	public int compareTo(City otherCity)
	{
		switch (sortBy) {
			case name:
			default:
				return this.name.compareTo(otherCity.name);
			case distance:
				return (int) (this.distance - otherCity.distance);
		}
	}

	public String toString()
	{
		return "CityOb <<" + name + "," + state +">>";
	}

}
