package com.eni.android.map;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class ListeMarqueurs extends ItemizedOverlay<OverlayItem> {

	private ArrayList<OverlayItem> overlayList;
	private Context context;

	public ListeMarqueurs(Drawable drawable, Context context) {
		super(boundCenter(drawable));
		overlayList = new ArrayList<OverlayItem>();
		this.context = context;
	}

	@Override
	protected OverlayItem createItem(int pos) {
		return overlayList.get(pos);
	}

	@Override
	public int size() {
		return overlayList.size();
	}

	public void addItemToOverlayList(OverlayItem item) {
		overlayList.add(item);
		populate();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			GeoPoint clicPosition = mapView.getProjection().fromPixels(
					(int) event.getX(), (int) event.getY());

			Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
			try {
				List<Address> addr = geoCoder.getFromLocation(
						clicPosition.getLatitudeE6() / 1E6,
						clicPosition.getLongitudeE6() / 1E6, 1);

				String clicAddr = "";
				if (addr.size() > 0) {
					for (int i = 0; i < addr.get(0).getMaxAddressLineIndex(); i++)
						clicAddr += addr.get(0).getAddressLine(i) + "\n";
				}

				Toast.makeText(context, clicAddr, Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		} else
			return false;
	}

}
