package com.example.TreballFiGrau;

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

import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class GoogleMaps extends Activity implements LocationListener {
	//Google Map
	public GoogleMap googleMap;
	public double latitude=41.386484;
	public double longitude= 2.164239;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.google_maps);
	    Log.d("aki", "dintre onCreate google maps");
	    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  		Log.d("aki", "11111");
  		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
  		Log.d("aki", "2222");
	    //initilizeMap();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		Log.d("aki", "dintre start google maps");
		initilizeMap();
	
	}
	
	/**
	 * function to load map. If map is not created it will create it for you
	 * */
	private void initilizeMap() {
		Log.d("aki", "initilizeMap");
	    if (googleMap == null) {
	    	googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
	    	googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
	    	    public boolean onMarkerClick(Marker marker) {
	    	        
	    	    	Log.d("aki", "marker click");
	    	        Toast toast = Toast.makeText(getBaseContext(), marker.getTitle(), Toast.LENGTH_LONG);
	        
	                toast.show();
	               
	    	        return false;
	    	    }
	    	});
	    	
	    	googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
	             @Override
	             public void onInfoWindowClick(Marker marker) {
	            	 Log.d("aki", "title click");
	            	 String c = marker.getSnippet();
	            	 int pos = Integer.parseInt(c);
	            	 
	            	 ArrayList<Noticia> llista = Llista_AdapterNoticies.entradas;
	            	 Noticia noti = llista.get(pos);
	            	 Log.d("aki", "title click");
	            	 NoticiaSeleccionada.cargarInformacio(noti);
	 				 Intent intent = new Intent(getBaseContext(), LlegirNoticia.class);
	 		         startActivity(intent);
	 		        Log.d("aki", "title click");
	            	 


	             }
	        });
	    	
	    	// permet girar el mapa crec
	    	//googleMap.getUiSettings().setRotateGesturesEnabled(true);
	    	
	    	//localotation button
	    	//googleMap.getUiSettings().setMyLocationButtonEnabled(true);
	    	Log.d("aki", "abans posicio");
	    	//agafarLocalitzacio();
	    	Log.d("aki", "actualitzar posicio");
	    	colocarMarker();
	    	Log.d("aki", "colocar amrkerr");
	    	canviarPosicioCamara();
	    	Log.d("aki", "posicio");

	        if (googleMap == null) {
	            Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
	        }
	    }
	}
	/*
	@Override
	protected void onResume() {
	    super.onResume();
	    Log.d("aki", "on resume");
	    initilizeMap();
	}
	*/
	
	public void agafarLocalitzacio(){
  		 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  		Log.d("aki", "11111");
  		 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
  		Log.d("aki", "22222");
  		 Location lol = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER);
  		Log.d("aki", "33333");
  		 //NoticiaCreada.latitude=lol.getLatitude() / 1E6;
  		 //NoticiaCreada.longitude=lol.getLongitude() / 1E6;
  		//Log.d("aki", "44444");
  		 //Log.d("aki", "agafarLocalitzacio:"+NoticiaCreada.latitude);
  		 //Log.d("aki", "agafarLocalitzacio:"+NoticiaCreada.longitude);
  	
  	}
	public void colocarMarker(){
		// latitude and longitude --- UB 41.386484, 2.164239   41.397494, 2.119929
		//double latitude = 41.386484;
		//double longitude = 2.164239;
		
		/*  AIXO FUNCIONA
		 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
		 Location lol = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER);
		 Log.d("aki", "despres codi");
		 latitude=lol.getLatitude() / 1E6;
		 longitude=lol.getLongitude() / 1E6;
		 
		 Log.d("aki","Latitude:");
		Log.d("aki","Longitude:");
		// create marker
		MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello UB ");
		Log.d("aki", "add amrker");
		MarkerOptions marker2 = new MarkerOptions().position(new LatLng(41.386484, 2.164239)).title("Hello UB ");
		Log.d("aki", "add amrker");
		// adding marker
		googleMap.addMarker(marker);
		googleMap.addMarker(marker2);
		 FINS AKI
		*/
		Log.d("aki", "codi");
		ArrayList<Noticia> llista =Llista_AdapterNoticies.entradas;
		for(int i=0;i<llista.size();i++){
			Noticia no = llista.get(i);
			Log.d("aki", "la:"+no.latitude);
			if (no.latitude!="0.0" && no.longitude!="0.0"){
				Log.d("aki", " if la:"+no.latitude);
				
				float la = Float.parseFloat(no.latitude);
				float lo = Float.parseFloat(no.longitude);
				MarkerOptions marker = new MarkerOptions().position(new LatLng(la,lo)).title(no.titol);
				String num = Integer.toString(i);
				marker.snippet(num);
				googleMap.addMarker(marker);
				
			}
		}
		
	}
	
	
	
	
	public MarkerOptions canviarColorMarker(MarkerOptions marker){
		marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
		return marker;
	}
	
	public void canviarPosicioCamara(){
		CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
		googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
	}
	
	public void canviarMapaType(){
		googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
	}
	
	public void ciutatLocalitzacio() throws IOException{
		Log.d("aki", "111111111");
		Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
		Log.d("aki", "2222222222");
		List<Address> addresses =  gcd.getFromLocation(41.386484, 2.164239, 1);
		if (addresses.size() > 0){ 
		    
			Log.d("aki",addresses.get(0).getCountryName());
			Log.d("aki",addresses.get(0).getLocality());
			Log.d("aki",addresses.get(0).getSubLocality());
		}
	}
	
	

	@Override
	public void onLocationChanged(Location location) {
		Log.d("aki", "onLocationChanged");
		Log.d("aki","Latitude:" + location.getLatitude()/ 1E6);
		Log.d("aki","Longitude:" + location.getLongitude()/ 1E6);	
		NoticiaCreada.latitude=location.getLatitude()/ 1E6;
		NoticiaCreada.longitude=location.getLongitude()/ 1E6;
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.d("Latitude","status");
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.d("Latitude","enable");
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.d("Latitude","disable");
		
	}

}

