package com.qiyou.mb.android.ui.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; 
import android.widget.AdapterView.OnItemClickListener;

import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.PoiAddrInfo;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.share.OnGetShareUrlResultListener;
import com.baidu.mapapi.search.share.PoiDetailShareURLOption;
import com.baidu.mapapi.search.share.ShareUrlResult;
import com.baidu.mapapi.search.share.ShareUrlSearch;
 
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.basic.Activity_bean;
import com.qiyou.mb.android.beans.basic.GEOaddress;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.base.IlocationFragment;
import com.qiyou.mb.android.utils.log.QLog;

public class LocationPickerFragment extends Route_fragment implements
		IlocationFragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
		  vContainer = inflater.inflate(R.layout.location_picker, container, false);
		  activity.updateActionBarTitle(R.string.frg_route);	   
		
		  setFTag();
		  initialViews();
		return vContainer;
		}
	
	 @Override
	  public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
	    activity.geoAddress= new GEOaddress();
//	    activity.latToshow 
// 		activity.lngToshow  
	    canLocationMap = true;
	    locationInMap(null);
	    locateMapCenter( activity.latToshow,activity.lngToshow);
	  
	   
 
	  mBaiduMap.setOnMapStatusChangeListener( new OnMapStatusChangeListener() {  
	        /** 
	        * 手势操作地图，设置地图状态等操作导致地图状态开始改变。 
	        * @param status 地图状态改变开始时的地图状态 
	        */  
	        public void onMapStatusChangeStart(MapStatus status){  
	        }  
	        /** 
	        * 地图状态变化中 
	        * @param status 当前地图状态 
	        */  
	        public void onMapStatusChange(MapStatus status){  
	        }  
	        /** 
	        * 地图状态改变结束 
	        * @param status 地图状态改变结束后的地图状态 
	        */  
	        public void onMapStatusChangeFinish(MapStatus status){  
	        	loadPOIs();
	        }  
	    });
	 }
	 
	@Override
	 protected void routeInitial(){
		 
	 }
	 
	 private ListView lvAdreess = null; 
	 QSimpleAdapter   addressSimpleAdapter;
	boolean isStartNetLocaiton =false;
	
	EditText txtSelectedName;
	TextView textSelectedAdress;
//	TextView textSelectedAdress;
	Button btn_locationConfirm; 
	double lat ;
    double lng ;
    String uid="";
    private ShareUrlSearch mShareUrlSearch = null;
    private GeoCoder mGeoSearch;
    
    boolean canLoadPoi = true;
	  // 条目上单击处理方法.  
    OnItemClickListener itemListener = new OnItemClickListener() {  
        @Override  
        public void onItemClick(AdapterView<?> parent, View view, int position,  
                long id) {  
        		selectedAddressItem =position;
        		addressSimpleAdapter.setSelectItem(position);
        		addressSimpleAdapter.notifyDataSetInvalidated(); 
        	   
//        		lvAdreess.setSelection(position);
  			    HashMap<String, String> localHashMap = (HashMap<String, String>) addressSimpleAdapter.getItem(position); 
  			     String pt =localHashMap.get("pt")  ; 
  			    String[] latlng =pt.split(",");
//  			    int lat =Integer.parseInt(latlng[0]);
//  			    int lng=Integer.parseInt(latlng[1]);
  			    uid =localHashMap.get("uid");
  			    double lat =Double.parseDouble(latlng[0]);
			    double lng=Double.parseDouble(latlng[1]);
			    canLoadPoi = false;
  			    if(canLocationMap){
  			      locationInMap(null);
  			    	
  			    }
  			    
  			    
//   		      mMapController.setCenter(new GeoPoint(	lat,	lng));
//			  mMapView.refresh();
			  
  			  locateBaiduMapCenter(lat,	lng);
			  setSelectedText( position);
  			    
        }

	 
    };  
    
  /*  @Override
    void loadPtAdrress(LatLng gp){
     	mPoiSearch.reverseGeocode(gp); 
     }*/
	
	@Override
	public void updateUI(Location location, Boolean isOnPause){
		
		updateMapView(location);
		   
		
		  
	}
	
	@Override
	 protected void initalLvs(){
		 
	 }
	
	 
	 @Override
	  protected void initialViews(){	
		 initialMapview();
//		 initialMkSearch(); 
		 initalFinderViews();
	
		 lvAdreess =(ListView)vContainer.findViewById(R.id.loc_list);  
		 lvAdreess.setOnItemClickListener(itemListener);
		 
		  txtSelectedName =(EditText)vContainer.findViewById(R.id.text_selected_address_name); 
		  textSelectedAdress=(TextView)vContainer.findViewById(R.id.text_selected_address);
		  btn_locationConfirm=(Button)vContainer.findViewById(R.id.btn_location_confirm);
		  btn_locationConfirm.setOnClickListener(ButtonOnClickListener);
		  
		  rt_cross =(ImageView) vContainer.findViewById(R.id.rt_cross);
		  rt_cross.setVisibility(View.VISIBLE);
			 
		  initialPoiSearch();
		  mShareUrlSearch = ShareUrlSearch.newInstance();
	      mShareUrlSearch.setOnGetShareUrlResultListener(

	    		  new OnGetShareUrlResultListener(){

					@Override
					public void onGetLocationShareUrlResult(ShareUrlResult result) {
						processShareUrl(result);
					}

					@Override
					public void onGetPoiDetailShareUrlResult(ShareUrlResult result) {
						processShareUrl(result);
					}

					@Override
					public void onGetRouteShareUrlResult(ShareUrlResult arg0) {
 						
					}
	    			  
	    		  }
	    		  
	    		  );
	      
	      
	  	mGeoSearch = GeoCoder.newInstance();
	  	mGeoSearch.setOnGetGeoCodeResultListener(

				new OnGetGeoCoderResultListener(){

					@Override
					public void onGetGeoCodeResult(GeoCodeResult arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onGetReverseGeoCodeResult(
							ReverseGeoCodeResult result) {
					 
						processAddress(result);
					}
					
				}
				);
	        
	 }
	 
	 
	 @Override
	    void pickLocation(){
		 
		 if(activity.addressComponent==null) return;
		    
				    
		    
	    	activity.geoAddress= new GEOaddress();
	    	activity.geoAddress.setCity(activity.addressComponent.city); 
	    	activity.geoAddress.setDistrict( activity.addressComponent.district);
	    	activity.geoAddress.setProvince(activity.addressComponent.province);
	    	activity.geoAddress.setStreet(activity.addressComponent.street);
	    	activity.geoAddress.setStreetNo(activity.addressComponent.streetNumber);
	    	activity.geoAddress.setName(txtSelectedName.getText().toString());
	    	activity.geoAddress.setAddress(textSelectedAdress.getText().toString()); 
//	    	activity.geoAddress.setLat((float) Utils.getggLat(lat/1e6, lng/1e6 ));
//	    	activity.geoAddress.setLon( (float) Utils.getggLon(lat/1e6, lng/1e6));
	    	activity.geoAddress.setLat((float) Utils.getggLat(lat, lng ));
	    	activity.geoAddress.setLon( (float) Utils.getggLon(lat, lng));
	    	if(TextUtils.isEmpty(activity.geoAddress.getName().trim())){
	    		txtSelectedName.setEnabled(true);
		    	txtSelectedName.setSelected(true);
		    	txtSelectedName.requestFocus();
	    	}else{
	    		 activity.sharedAddressUrl ="";
	 		    LatLng gp = new LatLng(lat,lng);
	 		    QLog.getLogger().d(dTAG, " to share url lat,lng is" +lat +" , "+lng);
	 		   mShareUrlSearch.requestPoiDetailShareUrl(new PoiDetailShareURLOption().poiUid(uid)) ;
	 		   //.poiRGCShareURLSearch(gp ,  "爱骑驴分享-"+ activity.geoAddress.getName(),activity.geoAddress.getAddress());

	    	}
//			 onBack();
	    	
	    }
	    
	
	 @Override
	protected
	 void showMapViews(){
		 
	 }
	
	 @Override
	 void loadPOIs(){
// 		 GeoPoint gp = mMapView.getProjection().fromPixels(mMapView.getCenterPixel().x,mMapView.getCenterPixel().y );
//		  mBaiduMap.getMapStatus().targetScreen;
//  		 mPoiSearch.searchNearby(new PoiNearbySearchOption().location( mBaiduMap.getMapStatus().target).keyword(""));
  		if (canLoadPoi){
  			mGeoSearch.reverseGeoCode(new ReverseGeoCodeOption().location(mBaiduMap.getMapStatus().target));
   		}
  		canLoadPoi = true;
	  }
	 int 	selectedAddressItem  =-1;
	 
 void processAddress(ReverseGeoCodeResult res){
		 
		 selectedAddressItem=-1;
		 addressData = new ArrayList<Map<String, String>>();
		
		 if(res==null){
			 // list clear
			 
			 return;
		 }
//		 activity.sharedAddressUrl ="";
//		 mSearch.poiRGCShareURLSearch(res.geoPt, "爱骑驴位置分享","");
		 Map<String, String> t;// = new HashMap<String,String>();			 
		 
		 if(res.getPoiList()!=null){
			 for( PoiInfo info : res.getPoiList() ){
	             	if ( info.location != null ){
	             		QLog.getLogger().d(dTAG, info.address);
	//             		mMapView.getController().animateTo(info.pt);
	//             		break;
	             		 t = new HashMap<String,String>();	
	             		 t.put("name", info.name);
	             		 t.put("address", info.address );
	             		 t.put("pt", info.location.latitude+","+info.location.longitude);
	             		 t.put("uid", info.uid);
	             		addressData.add(t);
	             	}
	             }
		 }else{
				QLog.getLogger().d(dTAG, res.getAddress());
				 t = new HashMap<String,String>();	
				 t.put("name", res.getBusinessCircle());
				 t.put("address", res.getAddress() );
         		 t.put("pt", res.getLocation().latitude+","+ res.getLocation().latitude);

         		addressData.add(t);
				
		 }
		 
		 activity.addressComponent= res.getAddressDetail();
		 selectedAddressItem=0;
		 showAddressData();
		 if(canLocationMap){
			      locationInMap(null); 
		  }
		
	 }
 
	 
	/* @Override
	 void processAddress(PoiResult result ){
		 
		 super.processAddress(result);
		 
		 selectedAddressItem=-1;
		 addressData = new ArrayList<Map<String, String>>();
		
		 if(result==null){
			 // list clear
			 
			 return;
		 }
//		 activity.sharedAddressUrl ="";
//		 mPoiSearch.poiRGCShareURLSearch(res.geoPt, "爱骑驴位置分享","");
		 Map<String, String> t;// = new HashMap<String,String>();			 
		 
		 if(result.getAllAddr()!=null){
			 for( PoiAddrInfo info : result.getAllAddr()){
	             	if ( info.location!= null ){
	             		QLog.getLogger().d(dTAG, info.address);
	//             		mMapView.getController().animateTo(info.pt);
	//             		break;
	             		 t = new HashMap<String,String>();	
	             		 t.put("name", info.name);
	             		 t.put("address", info.address );
	             		 t.put("pt", info.location.latitude+","+info.location.latitude); 
	             		addressData.add(t);
	             	}
	             }
		 }else{
//				QLog.getLogger().d(dTAG, result.strAddr);
				 t = new HashMap<String,String>();	
				 t.put("name", result.);
				 t.put("address", res.strAddr);
         		 t.put("pt", res.geoPt.getLatitudeE6()+","+ res.geoPt.getLongitudeE6());

         		addressData.add(t);
				
		 }
//		 activity.addressComponent= result.//res.addressComponents;
		 selectedAddressItem=0;
		 showAddressData();
		 if(canLocationMap){
			      locationInMap(null); 
		  }
		 
	 }*/
	
 
	 void processShareUrl (ShareUrlResult res){
			 activity.sharedAddressUrl =""; 
			 if(res==null){
				 
	 		     QLog.getLogger().d(dTAG, " return res is null") ;
	
	//			 return;
			 }else { 
				 activity.sharedAddressUrl =res.getUrl();
				 QLog.getLogger().d(dTAG, "return url is "+res.getUrl()) ;
			 }
			
			 onBack();
		 }
	 
	  
	     List<Map<String, String>> addressData;
		
		 int currentActRow=0;
		protected void showAddressData( ){
			 
			addressSimpleAdapter = new QSimpleAdapter(activity,addressData,R.layout.simple_lv_detail,
							new String[]{ 
											"name",
											"address",
											"pt"
										},
							new int[]{ 
										R.id.simple_lv_name,
										R.id.simple_lv_address,
										R.id.simple_lv_value		
	        						}); 
		   
			  
			lvAdreess.setAdapter(addressSimpleAdapter);   
			addressSimpleAdapter.setSelectItem(	selectedAddressItem   );
			lvAdreess.setSelection(selectedAddressItem); 
			setSelectedText(selectedAddressItem);
		 }
	 
	  
		
		void setSelectedText(int position){
			HashMap<String, String> localHashMap = (HashMap<String, String>) addressSimpleAdapter.getItem(position); 
			     String pt =localHashMap.get("pt")  ; 
			    String[] latlng =pt.split(",");
//			     lat =Integer.parseInt(latlng[0]);
//			     lng=Integer.parseInt(latlng[1]);
			    lat =Double.parseDouble(latlng[0]);
				lng=Double.parseDouble(latlng[1]);
				    
//			    String name =localHashMap.get("name")  ;
//			    String address =localHashMap.get("address")  ;
			    txtSelectedName.setText(localHashMap.get("name"));
			    textSelectedAdress.setText(localHashMap.get("adress"));
			    txtSelectedName.setEnabled(false);
			    if(TextUtils.isEmpty(txtSelectedName.getText())){
			    	txtSelectedName.setEnabled(true);
			    	txtSelectedName.setSelected(true);
			    }
//			    activity.sharedAddressUrl ="";
//			    GeoPoint gp = new GeoPoint(lat,lng);
//			    mPoiSearch.poiRGCShareURLSearch(gp , "爱骑驴位置分享爱骑驴位置分享爱骑驴位\n置分享爱骑驴位置分享爱骑驴位置分享xfsf",txtSelectedName.getText().toString());
		}
		
		
		
	
	 @Override
		public void setFTag(){
			TAG="com.qiyou.LocaitonPicker_fragment";
		}
		public static String getFTag(){
			return "com.qiyou.LocaitonPicker_fragment";
		}
		@Override
		public String getCurrentTag(){
			
//			   QLog.getLogger().e(dTAG,TAG+" Track_fragment, app.currentActiveFragment: "+activity.app.currentActiveFragment);
			return "com.qiyou.LocaitonPicker_fragment";
			
		}	
	
	
		@Override
		public void onResume() {
			super.onResume();
			activity.app.updateUIstatus(true);
			 
		/*	isStartNetLocaiton = !activity.app.isNetworkLocationRequestStarted;
			
		
				
			  if(!Utils.isNetworkConnected(activity) && !Utils.isGpsEnabled(activity)){
				  Toast.makeText(activity, "地图定位需要开启GPS或网络连接", Toast.LENGTH_SHORT).show();    
			  }
				if(isStartNetLocaiton) { //started
//					activity.app.startAndroidGPSRequest();			  
			  		activity.app.startNetworkLocationRequest(false);
			  		
				}*/
 				activity.app.isLocationFinding=true;
//				activity.app.startNetworkLocationRequest(false);
			
		}
	 
	 @Override
		public void onPause() { 
			super.onPause();  
			activity.app.updateUIstatus(false);
			/*if(isStartNetLocaiton) { //started
//				activity.app.startAndroidGPSRequest();			  
		  		activity.app.stopNetworkLocationRequest();
		  		
			}
			*/
//			activity.app.stopNetworkLocationRequest();
 			activity.app.isLocationFinding=false;
			
		}
	 @Override
		public void onDestroy() {  
			super.onDestroy();
		}
	
	 @Override
	 void tabOnresume(){
		 
	 }
	 @Override
	 void routeResume(){
		 
	 }

}
