package com.selbor.location;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Point;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.net.http.RequestQueue;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;

public class MiniLocationMap extends MapActivity {
	
	private MapView mMapView;
	private MapController mMapController;
	private RequestQueue mRequestQueue;
	private Handler mHandler = new Handler(){

		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			if(msg.what == 123){
				DemoLocation currentLocation = (DemoLocation) msg.getData().get("location");
				mMapController.centerMapTo(new Point(currentLocation.lat, currentLocation.lon), true);
			}
		}
		
		
	};
	private LocationHistoryOverLay overlay;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        mRequestQueue = new RequestQueue(this);
        mMapView = new MapView(this);
        this.setContentView(mMapView);
        
        mMapController = mMapView.getController();
        mMapController.zoomTo(15);
       
        
    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, 0, "Retrieve Locations", new Runnable(){

			public void run() {
				 Map headers = new HashMap();
				mRequestQueue.queueRequest(
		                "http://10.0.0.199:8080/endpoint",
		                "GET", headers, new LocationListHandler(mHandler), null, 0, false);
			}
			
			
		});
		
		menu.add(0, 1, "Post Current Location", new Runnable(){

			public void run() {
				
				// get current location and use it as params to our API call
				LocationManager locMan = (LocationManager) MiniLocationMap.this
						.getSystemService(Context.LOCATION_SERVICE);
				Location loc = locMan.getCurrentLocation("gps");
				
				 Map headers = new HashMap();
		        
		        String text= "lat=" +(int)(loc.getLatitude()*1E6) + "&lon=" + (int)(loc.getLongitude()*1E6);
		       
		        byte[] bytes = text.getBytes();
		        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
				mRequestQueue.queueRequest(
		                "http://10.0.0.199:8080/endpoint",
		                "POST", headers, new LocationEventHandler(mHandler), bais, bytes.length, false);
			}
			
			
		});
		
		return super.onCreateOptionsMenu(menu);
	}
}