package com.qiyou.mb.android.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mapapi.model.LatLng;
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.geocode.ReverseGeoCodeResult.AddressComponent;
import com.google.gson.Gson;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.GEO_bean;
import com.qiyou.mb.android.beans.basic.GEOaddress;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.content_providers.TrackProvider;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;

public class TrackGEOService extends IntentService implements OnGetGeoCoderResultListener {
     
	GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	 
	public final static String TAG="com.qiyou.TrackGEOService";
	public static final String dTAG ="com.qiyou";
	protected QiYouApplication app;
	int topWaiting=0;
	boolean isBreak=false;
	boolean isContinue=false;
	Track track;
	int trackId =-1;
	int trackGeoType=-2;
	int networkErrors=0;
	int geoCnt=0;
//	float trackDist=0;
	String pathPoints="";
//	boolean canUpdate =false;
	
	protected ContentResolver contentResolver;
	protected String[] projection;
	 
	
	int width ;
	int height ;
	/*String center="";
	String pathStyle ;
	String format;
	String staticMapUrl;
	String baiduUrl ="http://api.map.baidu.com/staticimage";*/
	String whereUserId;
	boolean isSpecifiedTrackMap=false;
	public TrackGEOService( ) {
		super(TAG);
		// TODO Auto-generated constructor stub
		
		 
	}
	public TrackGEOService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
		
	}
	 @Override
	public void onCreate() {
		    super.onCreate();
		    app =(QiYouApplication)this.getApplication();
		    whereUserId =" and " +TrackProvider.KEY_TRACK_USER_ID +" = " +app.user.getUserbean().getId();
		    contentResolver = getContentResolver();		    
//		    initialStaticMapParameters();
		    
		 // 初始化搜索模块，注册事件监听
			mSearch = GeoCoder.newInstance();
			mSearch.setOnGetGeoCodeResultListener(this);
			
	 } 
	/* private void initialStaticMapParameters(){
		      width= QiYouConstant.PV_INT_SCREEN_WIDTH>0? QiYouConstant.PV_INT_SCREEN_WIDTH:720;
//		      width =width/2;
			  height=width/3;
			  center="";
			  pathStyle="0xff0000,5,1";
			  format ="?" 
//					+ center +"&" 
//					+"zoom=13&"  
					+"width=%s&height=%s&paths=%s&pathStyles=%s" +
					"&copyright=1";
	 }*/
	 
	@Override
	protected void onHandleIntent(Intent intent) {

		// TODO Auto-generated method stub
//
		  QLog.getLogger().d(dTAG, TAG+" app.geoWps.size():"+(app.geoWps!=null?app.geoWps.size():null)  );
//		if(Utils.getNetworkType(this)==QiYouConstant.NETWORK_TYPE_OFF) return;
		if(!QiYouConstant.NETWORK_CONNECTED 
				||  QiYouConstant.IS_PROCESSING_GEO_FOOTMARK
				|| app.geoWps!=null && app.geoWps.size()>0
				)
			return;
	    
		QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =true;
		populateGEOs(0);//populate the province list 
		isSpecifiedTrackMap=false;
		String key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID; 
		 
		    //get specified track by id
		    if (intent.hasExtra(key)) {
		    	trackId = intent.getExtras().getInt(key);
		    	isSpecifiedTrackMap=true;
		    	updateTrackGEO();
		    	return;
		    } 
             
		    key = QiYouConstant.EXTRA_KEY_TRACK_GEOS;  
	         if (intent.hasExtra(key)) {
	        	 trackId=-1;
	        	 app.setlastGeoRequestTime();
	 		     updateTrackGEO();	 		       	
	 		     return;	 		    	
	 		    }
	        
	         
             key =  QiYouConstant.ACTION_CONNECTIVITY_CHANGE ;  
           
	         if (intent.hasExtra(key)) {
//	        	 if(!Utils.canUpdateGEOfootmark(this) ){
////	        		 if(app.lastWifiTime>0 || System.currentTimeMillis()-app.lastWifiTime <30*1000){
////	        		 Log.e(dTAG, TAG+" 检测到上次联网更新 GEO在30秒内，本次不再执行。" );
//	        		 return;
//	        	 }
//	        	 
	        	
	        	 QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =true;
	        	 app.setlastGeoRequestTime();	
	        	 
	        	 trackId=-1;
 		    	 updateTrackGEO();  
 		    	 
 		    	 
 		    	 
 		    	 app.setlastGeoRequestTime();	
 		    	 
// 		    	 app.checkVersionUpdate(); 
 		    	 return;	 		    	
	 		    } 
	         
	      
	         
	         
	         
	         //after the geo, to start the offlineMap service.
//	         app.startNetworkLocationRequest();
	         
	        
	} 
	
	void updateRoadWps(){
	 long lastTime=0;
	  
	 /*CopyOnWriteArrayList<Waypoint_bean>  wbs=new CopyOnWriteArrayList<Waypoint_bean>();*/
	  ArrayList<Waypoint_bean>  wbs=new  ArrayList<Waypoint_bean>(); 
		 
		 for(Waypoint_bean wb:track.getTrackBean().getRoadWps() ){ 
			 
			 if(wb==null)continue;
			 
			if(wb!=null && wb.getTime()>lastTime|| wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt())
				wbs.add(wb);
			else{
				// QLog.getLogger().d(TAG, "wb==null :"+(wb==null));
				// QLog.getLogger().d(TAG, "wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt() :"+(wb.getTurnFlag()!=null && wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()));
				// QLog.getLogger().d(TAG, "wb.getTurnFlag().toInt() :"+wb.getTurnFlag().toInt());  
			}
				//				tb.getRoadWps().remove(wb);
			if(wb!=null)lastTime =wb.getTime();
			 
		 }
		 if(wbs.size()<track.getTrackBean().getRoadWps().size()) track.getTrackBean().setRoadWps(wbs);
		 
	}
	
	 
	
	  int newGEOcnt=0;
	void updateTrackGEO(){
		 HashMap<Integer,String[]> geoWps = new HashMap<Integer,String[]>();   
             String[] wps ;
            //     QLog.getLogger().d(dTAG, TAG+" 开始geo数据处理"  );
             if(trackId >0 && trackId == app.getCurrentTrack().getTrackBean().getTrackId()){
            	 track = app.getCurrentTrack();            	 
            	 if(track.getTrackBean().getRoadWps().size()==0) return;
            	 track.getTrackBean().setTrackId(trackId); 
//            	 trackDist =track.getLastWp().getWb().getSumDist();
            	
            	 updateRoadWps();
          /*       ArrayList<Waypoint_bean> roadWps =new  ArrayList<Waypoint_bean>();
                 
            	if( track.getTrackBean().getType()==TrackType.GPX){  
	            
	          	   for(Waypoint_bean wb:track.getTrackBean().getRoadWps()){ 
	          			if(wb==null)continue;
	          			 QLog.getLogger().d(dTAG,TAG+" 1 wb turnflag is "+  wb.getTurnFlag()  ); 
	          			if(    wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){ 
	          				   roadWps.add(wb);
	          				  
	          			} 
	          			
	          		 }
            	}else{
            		roadWps=track.getTrackBean().getRoadWps();
            	}
            	 */
            	 wps = new String[5];
//                 wps[0] = buildRoadBookGEO(roadWps);
            	 wps[0] = buildRoadBookGEO(track.getTrackBean().getRoadWps());
  				 wps[1] = buildWoGEO(track.getStartWp());
  				 wps[2] = buildWoGEO(track.getLastWp());
  				 wps[3] = buildWoGEO(track.getMaxDistWp()); 	
  				
// 			     geoWps.put(trackId, wps);
 			   
 			   
 			   networkErrors=generateStaticMap(track)?networkErrors:networkErrors+1;
 			   if(geoCnt>0) wps[4] = String.valueOf(networkErrors); 
 			   
 			  if(newGEOcnt>0){
			    	 geoWps.put(trackId, wps);
					track.TruncateFootMark();
					newGEOcnt =0;
				}
			    
 			   
               }else{
            	   Cursor cursor =getWps();
                   try {	       
                	  //     QLog.getLogger().d(dTAG, TAG+" 共"+cursor.getCount() +" 条track记录需要更新。" );
         		      if (cursor.moveToFirst()) {
         		    	  int processedCnt =0;
         		    	  while(processedCnt < cursor.getCount()){
         		    		 networkErrors=0;
         		    		 geoCnt=0;
         		    		 trackId =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID));
	         		     	  String rdBearJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS));
//	         			      track =new Track(null,null, rdBearJson,null);
//	         			      track.getTrackBean().setTrackId(trackId);
	         			      track =new Track(trackId,false,rdBearJson, null);
//	         		     	 track =new Track(trackId,false,null, null);
	         		    	  track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP)));
	         		    	  track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP)));
	         		    	  track.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP)));
	         		    	  track.getTrackBean().setType(TrackType.valueOf( cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE))));
	         		    	 track.getTrackBean().setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR)));
//	         		    	   trackDist =track.getLastWp().getWb().getSumDist();
	         		    
	         		    	 // QLog.getLogger().d(dTAG, TAG+" -------------------------------------正在处理track： "+ trackId);
	         		    	 
	         		    	   updateRoadWps();
	         		    	  
	         		    	  wps = new String[5];
	         		    	  wps[0] = buildRoadBookGEO(track.getTrackBean().getRoadWps());
	           			 	  wps[1] = buildWoGEO(track.getStartWp());
	           				  wps[2] = buildWoGEO(track.getLastWp());
	           				  wps[3] = buildWoGEO(track.getMaxDistWp()); 
	           				  
//	           				 geoWps.put(trackId, wps);
	           			
	           				processedCnt++; 	
	           				
		           		  
		      			   networkErrors=generateStaticMap(track)?networkErrors:networkErrors+1;
		     			   if(geoCnt>0) wps[4] = String.valueOf(networkErrors); 
		     			  if(newGEOcnt>0){
	           					geoWps.put(trackId, wps);
	           					track.TruncateFootMark();
	           					newGEOcnt =0;
	           				}
		      			   cursor.moveToNext();
         		    	  }
         		      } 
         		      }catch(Exception er)
         		      {
         		    	  Utils.logStackTrace(er, dTAG);
         		      }
         		      finally {
         		       if(cursor!=null) cursor.close();
         		      }
                   
                   	 genStaticMap4gpx(); 
               }
            
			 
//			 boolean canUpdate = true; //wps!=null && wps[0].length()>0 || wps[1].length()>0  || wps[2].length()>0 || wps[3].length()>0;
//			 if(canUpdate && geoWps.keySet().size()>0){	
             if( geoWps.keySet().size()>0){
		      /* Intent serviceIntent = new Intent(app, TrackDbServiceBackground.class);
//		       serviceIntent.putExtra(QiYouConstant.UPDATE_TRACK_GEO, true);
//		       serviceIntent.putExtra( QiYouConstant.EXTRA_KEY_ID, Integer.valueOf(trackId));  
			   serviceIntent.putExtra( QiYouConstant.EXTRA_KEY_TRACK_GEOS, geoWps);	      
			   startService(serviceIntent);	*/
               
//            	 app.getStaticsTracks();
             	 app.updateGEOs(geoWps);
            	 
		       QLog.getLogger().d(dTAG, TAG+" --------------------已提交数据更新. "  );
					 
			 }else{
				 QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =false;
			 }
			
 		
			      // QLog.getLogger().d(dTAG, TAG+" 本次GEO处理结束.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  );
 			      app.syncStatistics();
			      // QLog.getLogger().d(dTAG, TAG+" xxxxxxxxxxxx XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  );

	}
	
	
	
	
	String buildWoGEO(Waypoint wp){
		String wpJson ="";
		if(wp.getWb()!=null && wp.getWb().getGeo()==null && getGEOinfo(wp.getWb().getLatitude(),wp.getWb().getLongitude())){
			 GEOaddress geo= new GEOaddress();
			 geo.setProvince(GEOadress.province);
			 geo.setCity(GEOadress.city);
			 geo.setDistrict(GEOadress.district);
			 geo.setStreet(GEOadress.street);
			 geo.setStreetNo(GEOadress.streetNumber);	
			 geo.setLat(wp.getWb().getLatitude());
			 geo.setLon(wp.getWb().getLongitude());
			 wp.getWb().setGeo(geo);
			 wpJson =wp.toJsonWp();
			 if(!TextUtils.isEmpty(geo.toString("，"))){
				 newGEOcnt++;
			 }
			 
		}
			return wpJson; 
	}
	
	
	
	boolean getGEOinfo(Float lat,Float lon){   
		
		 isBreak=false;
		 isContinue=false;
		 topWaiting =0;
//        app.getBdGEOadress(lat,lon);
		  
//		 QLog.getLogger().d(dTAG,TAG+ String.format(" app.getBdGEOadres lat: %s; lon: %s", lat,lon));

		/* app.*/getBdGEOadress(lat,lon);
        geoCnt++;
//	    while(GEOadress==null && !isGEOerror)
        while(true)
	     try {
			Thread.sleep(200); 
//			app.getBdGEOadress(lat,lon);
			topWaiting+=200;
		    
//			QLog.getLogger().d(dTAG,TAG+"get GEOadress waiting for  "+ topWaiting );

			if(/*app.*/GEOadress!=null && !/*app.*/isGEOerror){
//				     QLog.getLogger().d(dTAG,TAG+"GEOadress " + GEOadress.province+GEOadress.city+GEOadress.district);
				break;
			}
			if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB/3)
			{
				networkErrors++;
				//     QLog.getLogger().d(dTAG,TAG+" 获取地址超时. topWaiting: "+topWaiting);
				//     QLog.getLogger().d(dTAG,TAG+String.format("lat %s,lon %s,GEOadress==null?%s,isGEOerror?%s", lat,lon,GEOadress==null,isGEOerror));
				
				
					if(Utils.getNetworkType(this)==QiYouConstant.NETWORK_TYPE_OFF){
						isBreak =true;  
//						   Toast toast=	Toast.makeText(this, "获取地址失败,请检查网络." , Toast.LENGTH_LONG );
//	 				 	   toast.show();  
	 				 	   break;				
					  }else{
						    isContinue =true;
						    break;
						    
					  }
						

			}
		  } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
			} 
	 /*   if(!canUpdate){
	    	if(!(isBreak || isContinue))canUpdate=true;
	    }*/
	    return !(isBreak || isContinue);
		    
	}
	
//   String buildRoadBookGEO(CopyOnWriteArrayList<Waypoint_bean> _roadWps){
	 String buildRoadBookGEO( ArrayList<Waypoint_bean> _roadWps){
	   
	   long lastTime=0;
	  /* CopyOnWriteArrayList<Waypoint_bean> roadWps =new  CopyOnWriteArrayList<Waypoint_bean>();*/
	    ArrayList<Waypoint_bean> roadWps =new   ArrayList<Waypoint_bean>();
	   for(Waypoint_bean wb:_roadWps){ 
			if(wb==null)continue;
		
			if(  wb.getTime()>lastTime|| wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){ 
				 roadWps.add(wb);
				 lastTime =wb.getTime(); 
			} 
			
		 }
//		int topWaiting=0;
//		boolean isBreak=false;
//		boolean isContinue=false;
		
	/*   if(roadWps.size()>300){
		   roadWps=(ArrayList<Waypoint_bean>) roadWps.subList(0, 300);
		   
	   }*/
	   
	   if(roadWps.size()==0) return"";
		 
		String lastAddress="";
		
//		float skiptDist=0;
	    
//	    ArrayList<Waypoint_bean> geoWps = new ArrayList<Waypoint_bean>();
			/*  for(Waypoint_bean b:roadWps)
	        {
	        	if (null !=b)
	        		al.add(b);
	        } 
	    if(al.size()==0) return"";
	    */
	    Waypoint_bean wb;
	    Waypoint_bean lastWb = null;
//	    Waypoint_bean lastWb4map = null;
	    GEOaddress lastGeo  =new GEOaddress();;// new GEOaddress();;
//        final int MAXLATLNGS=50;
	     int geocnt=0;
//	     float stepValue =roadWps.size()>MAXLATLNGS &&trackDist>0 ?trackDist/MAXLATLNGS:0;  
//	     pathPoints="";
//	     float skipDist=0;
	     
//	    //     QLog.getLogger().d(dTAG, TAG+" roadWps.size() is " + roadWps.size() +"----------------------------");
//	    //     QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS );
//	    //     QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS );
	     
//	    //     QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue);
	     
		 for(int i=0;i<roadWps.size();i++) {
		    	  
				 wb = roadWps.get(i);
				 
				 if(wb==null)continue;
				 
				 if( wb.getGeo()!=null ||/*track.getTrackBean().getType()==TrackType.GPX*/ track.isLushu() &&  wb.getTurnFlag().toInt()<=wpFlag.CUST.toInt()){  
					 continue; //gpx type only calculate tent,rest bear.
				 }
				 
//				 QLog.getLogger().d(dTAG,TAG+" track.isLushu() "+ track.isLushu() ); 
//				 QLog.getLogger().d(dTAG,TAG+" track.getTrackBean()getCreator()： "+ track.getTrackBean().getCreator() ); 
//				 QLog.getLogger().d(dTAG,TAG+" 1 wb turnflag is "+  wb.getTurnFlag()  ); 
				 
				 lastWb	=lastWb==null?wb:lastWb;				 
//				 if(trackId==34)
				 {
					 
//					//     QLog.getLogger().d(dTAG, TAG+" No.i,wb.gettime():"+i+"," + Utils.getFormatedTime(wb.getTime()));
				 }
				/* lastWb4map=lastWb4map==null?wb:lastWb4map;
				 if (TextUtils.isEmpty(pathPoints)||wb.getTime()>lastWb4map.getTime())
				 if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK ||!track.isStaticMapExist()){
					 
//					//     QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime()));
//					//     QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist()));
					//     QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist);
//					//     QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist));
					 float f =wb.getSumDist()-lastWb.getSumDist()+skipDist;
					 if(TextUtils.isEmpty(pathPoints)||f>=stepValue){  
						 
						  pathPoints=pathPoints+Utils.getbdLon(wb.getLatitude(), wb.getLongitude())+","+Utils.getbdLat(wb.getLatitude(), wb.getLongitude())+";";
						  skipDist=0; 
					 }
					 else
						 skipDist =wb.getSumDist()-lastWb.getSumDist();
					 lastWb4map =wb;
				 }
				 
				 if(wb.getTime()<lastWb4map.getTime())continue;*/
//				 lastWb	=roadWps.get(i>0?i -1:i);	
//				 if(lastWb!=null)lastGeo =lastWb.getGeo();
//				 else lastGeo =new GEOaddress();
				 
				 if( lastWb.getGeo()!=null){
					 
					   if(lastWb.getGeo().getProvince()!=null &&  !lastWb.getGeo().getProvince().equalsIgnoreCase( lastGeo.getProvince()))
						  lastGeo.setProvince(lastWb.getGeo().getProvince());
					  if(lastWb.getGeo().getCity()!=null &&  !lastWb.getGeo().getCity().equalsIgnoreCase( lastGeo.getCity()))
						  lastGeo.setCity(lastWb.getGeo().getCity());
					  if(lastWb.getGeo().getDistrict()!=null &&  !lastWb.getGeo().getDistrict().equalsIgnoreCase( lastGeo.getDistrict()))
						  lastGeo.setDistrict(lastWb.getGeo().getDistrict());
					  if( lastWb.getGeo().getStreet()!=null && !lastWb.getGeo().getStreet().equalsIgnoreCase( lastGeo.getStreet()))
						  lastGeo.setStreet(lastWb.getGeo().getStreet());
					  if(lastWb.getGeo().getStreetNo()!=null && !lastWb.getGeo().getStreetNo().equalsIgnoreCase( lastGeo.getStreetNo())){
						  lastGeo.setStreet(lastWb.getGeo().getStreet());
						  lastGeo.setStreetNo(lastWb.getGeo().getStreetNo());
					  }	
				 
				 } 
			
				 
				
		 
//				 updateGEOs(lastGeo); //check if the geo exits or not, if not, insert to db.
				 
				 
		      if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK ||wb.getGeo() ==null) 
		      { 
				 
		    	  getGEOinfo(wb.getLatitude(),wb.getLongitude()) ;
				 
				    if(isBreak)break;
				    if(isContinue || isGEOerror){
//				    	Track.saveBear(wb);
				    	continue;
				    }
				    
				   if(!isGEOerror){ 					   
					   
					   if(   
							   (  wb.getTurnFlag()==wpFlag.MAXR 
								   || wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()
								   || wb.getTurnFlag()==wpFlag.TENT
								   || wb.getTurnFlag()==wpFlag.REST
								   || i == roadWps.size()-1
								   || i == 0
							   )
							   && TextUtils.isEmpty(GEOadress.streetNumber)){
						   if(!track.isLushu())
							   Track.saveBear(wb);
					   }
					   String address = GEOadress.district+GEOadress.street +GEOadress.streetNumber;
			/*		   if(TextUtils.isEmpty(lastAddress)){ 
						  
						   
						   GEOaddress geo= new GEOaddress();
						  
						   
						   if( !GEOadress.province.equalsIgnoreCase( lastGeo.getProvince()))
							   geo.setProvince(GEOadress.province);
						   if( !GEOadress.city.equalsIgnoreCase( lastGeo.getCity()))
							   geo.setCity(GEOadress.city);
						   if(  !GEOadress.district.equalsIgnoreCase( lastGeo.getDistrict()))
							   geo.setDistrict(GEOadress.district);
						   if(  !GEOadress.street.equalsIgnoreCase( lastGeo.getStreet()))
							   geo.setStreet(GEOadress.street);
						   if(  !GEOadress.streetNumber.equalsIgnoreCase( lastGeo.getStreetNo())){
							   geo.setStreet(GEOadress.street);
							   geo.setStreetNo(GEOadress.streetNumber);
						   }
						   
						   wb.setGeo(geo);						   
						   lastGeo =lastWb.getGeo()!=null?lastWb.getGeo():geo;
						   
						   
						   
					   }else 
						  */ 
						   
						   if(!lastAddress.equals(address) ) {  //丢弃重复geo点
						
//							   if(lastWb.getGeo()!=null)
//								   lastGeo =lastWb.getGeo() ;
							 
							   GEOaddress geo= new GEOaddress();
							   if( !GEOadress.province.equalsIgnoreCase( lastGeo.getProvince()) ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt()  )
								   geo.setProvince(GEOadress.province);
							   if( !GEOadress.city.equalsIgnoreCase( lastGeo.getCity())  ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() )
								   geo.setCity(GEOadress.city);
							   if(  !GEOadress.district.equalsIgnoreCase( lastGeo.getDistrict())  ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() )
								   geo.setDistrict(GEOadress.district);
							   if(  !GEOadress.street.equalsIgnoreCase( lastGeo.getStreet())  ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() )
								   geo.setStreet(GEOadress.street);
							   if(  !GEOadress.streetNumber.equalsIgnoreCase( lastGeo.getStreetNo())  ||wb.getTurnFlag().toInt()>wpFlag.CUST.toInt() ){
								   geo.setStreet(GEOadress.street);
								   geo.setStreetNo(GEOadress.streetNumber);  
							   } 
							  /* if(addressResult!=null && addressResult.poiList!=null && addressResult.poiList.get(0)!=null){
								   geo.setName(addressResult.poiList.get(0).name);
							   }*/
							   if(addressResult!=null && addressResult.getPoiList()!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){
								   geo.setName(addressResult.getPoiList().get(0).name);
							   }
							   wb.setGeo(geo);  
							 
							   if(!TextUtils.isEmpty(geo.toString("，"))){
								   geocnt++;
//						      if(wb.getGeo()!=null || wb.getTurnFlag() >2){	//maxR or end point need to be kept.
							   
		//					  if(wb.getGeo()!=null || wb.getTurnFlag()>2){  //0,start;-1,left;1,right;2,back;3,maxR;4,end 
//								   wb.setBearDist(wb.getBearDist()+skiptDist);  //丢弃重复geo点
//								   skiptDist=0;
								  
		//					        updateGEOs(geo); //check if the geo exits or not, if not, insert to db.
								   if(wb.getTurnFlag()!=null)
									   trackGeoType =wb.getTurnFlag().toInt();
//								     QLog.getLogger().d(dTAG,TAG+" wb turnflag is "+  wb.getTurnFlag());
								     
//								   if(wb.getGeo()!=null && !TextUtils.isEmpty(wb.getGeo().toString(","))) 
								   addNewTrackGeo(updateGEOs(wb), trackId,trackGeoType,wb.getTime());//check if the geo exits or not, if not, insert to db.	And if new streetNo then insert trackgeo relation ship table.
							        
	 						/*		   if(
										   ( lastWb.getGeo()==null || TextUtils.isEmpty(lastWb.getGeo().toString("，")))
										    && i>0 )
	 									   
 									   		lastWb.setRoadBook(  lastWb.getRoadBook().replace("\"", "") + ",    \n 到达："+ wb.getGeo().toString("，")   +"\""); 
 			 */
									   newGEOcnt++;
								  
							  }else{
								  
//								  skiptDist+=wb.getBearDist();
							  }
						
						   } else if(wb.getTurnFlag().toInt()>=wpFlag.CUST.toInt()){
							       GEOaddress geo= new GEOaddress();
								   
								   geo.setProvince(GEOadress.province);
							 
								   geo.setCity(GEOadress.city);
							 
								   geo.setDistrict(GEOadress.district);
							 
								   geo.setStreet(GEOadress.street); 
								   
								   geo.setStreetNo(GEOadress.streetNumber);  
								   if(addressResult!=null && addressResult.getPoiList()!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){
									   geo.setName(addressResult.getPoiList().get(0).name);
								   }
							   wb.setGeo(geo); 
						  }
					   lastAddress =  address; 
				   } 
		       } else
				  continue; 
		      lastWb	=wb;
		    }
		      
//		      if(j>0)
//		    	  geoWps.get(j-1).setRoadBook( ", 当前位置:："+ lastWb.getGeo().toString("，") +"\n"+  geoWps.get(j-1).getRoadBook().replace("\"", "")    +"\"");
				  
//		  geoWps.get(geoWps.size()-1).setRoadBook(   geoWps.get(geoWps.size()-1).getRoadBook().replace("\"", "") + ",    \n 到达重点位置："+  geoWps.get(geoWps.size()-1).getGeo().toString("，")   +"\"");
          String rdbs =""; 
          if(geocnt==0) return rdbs;          	
//          else if( app.tracks_cached.containsKey(trackId) && roadWps.size()>0){
          else if( app.getTrackCache().get(trackId)!=null && roadWps.size()>0){ 
				if(trackId == app.getCurrentTrack().getTrackBean().getTrackId() ){
					 app.getCurrentTrack().setBearWps(roadWps);
					 rdbs =app.getCurrentTrack().getRdWpsJson().toString(); 
					 // QLog.getLogger().d(dTAG,TAG+" roadbears "+  rdbs);
					 app.getTrackCache().put(trackId,  app.getCurrentTrack());
				 }else{
					 app.getTrackCache().get(trackId).setBearWps(roadWps);
				     rdbs =app.getTrackCache().get(trackId).getRdWpsJson().toString();	
				 }
			 }
			else{
					Gson gson = new Gson();	
				try{
					rdbs = gson.toJson(roadWps) ;	
				}catch(Exception e)
				{			
					Utils.logStackTrace(e, dTAG);
				} 
			}
		 
		    return rdbs; 
		 
	}
	  
	 
	 
	ArrayList<GEO_bean> gbs = new ArrayList<GEO_bean>(); 
	 public int  updateGEOs(Waypoint_bean wb){		
		 
		 
		 
		 int geoId =-1;
		 if(GEOadress == null) return geoId;
//		 if(TextUtils.isEmpty(lastGeo.toString(","))) return geoId;
		 
		 if(TextUtils.isEmpty(GEOadress.province)){
			 return geoId;
		 } 
		 
		 //check province
		 int provinceId =0;
		 int cityId=0;
		 int districtId=0;
		 int streetId=0;
		
		 if( !app.geos.provinces.containsKey(GEOadress.province) ){
			  GEO_bean gb = new GEO_bean();
			  gb.setGeoType(QiYouConstant.GEO_PROVINCE);
			  gb.setName(GEOadress.province);
			  gb.setParentId(0);
			  provinceId =addNewGeos(gb);
			  app.geos.cities.clear();
			  app.geos.GEOcities.clear();
			  app.geos.districts.clear();
			  app.geos.GEOdistricts.clear();
			  app.geos.streets.clear();
			  app.geos.GEOstreets.clear();
			  app.geos.streetNos.clear();
			  app.geos.GEOstreetNos.clear();
		 }else{
			 provinceId =app.geos.provinces.get(GEOadress.province);
			 
			 //check if the cities are under the province, if not,clear and populate the cities.
			 if(app.geos.GEOcities.size()==0 
					 || app.geos.GEOcities.size()>0 
					 && app.geos.GEOcities.get(app.geos.cities.keySet().toArray()[0].toString()).getParentId()!=provinceId ){
				 app.geos.cities.clear();
				 app.geos.GEOcities.clear();
				 populateGEOs(provinceId);
				//     QLog.getLogger().d(dTAG, TAG+ " Populate province "+ GEOadress.province);
			 }
		 }
		 
		 
		 if(TextUtils.isEmpty(GEOadress.city)){
			 return geoId;
		 } 
		 
		 if(  !app.geos.cities.containsKey(GEOadress.city)){
			/* if(provinceId ==0){
				 if(lastGeo.getProvince()==null)return;
				  provinceId =app.geos.provinces.get(lastGeo.getProvince()); 
			  }
			 if(!app.geos.GEOprovinces.get(lastGeo.getProvince()).getName().equalsIgnoreCase(lastGeo.getProvince())){
				  app.geos.cities.clear();
				  populateGEOs(provinceId);
				 }
			  
			  if(!app.geos.cities.containsKey(lastGeo.getCity()))*/{
				  GEO_bean gb = new GEO_bean();
				  gb.setGeoType(QiYouConstant.GEO_CITY);
				  gb.setName(GEOadress.city);			 
				  gb.setParentId(provinceId); 
				  cityId =addNewGeos(gb); 
				  app.geos.districts.clear();
				  app.geos.GEOdistricts.clear();
				  app.geos.streets.clear();
				  app.geos.GEOstreets.clear();
				  app.geos.streetNos.clear();
				  app.geos.GEOstreetNos.clear();
			  }
			    
		 }else{
			 cityId =app.geos.cities.get(GEOadress.city);
			 if(app.geos.GEOdistricts.size()==0 
					 || app.geos.GEOdistricts.size()>0 
					 && app.geos.GEOdistricts.get(app.geos.districts.keySet().toArray()[0].toString()).getParentId()!=cityId ){				
				 app.geos.GEOdistricts.clear();
				 app.geos.districts.clear();
				 populateGEOs(cityId);
				//     QLog.getLogger().d(dTAG, TAG+ " Populate city "+GEOadress.city);
			 }
			 
			 
		 }
		 
		 if(TextUtils.isEmpty(GEOadress.district)){
			 return geoId;
		 } 
		 

		 if( !app.geos.districts.containsKey(GEOadress.district) ){
			/* if(cityId ==0){
				 if(lastGeo.getCity()==null)return;
				 cityId =app.geos.cities.get(lastGeo.getCity());  
			  }
			  if(!app.geos.GEOcities.get(lastGeo.getCity()).getName().equalsIgnoreCase(lastGeo.getCity())){
				  app.geos.districts.clear();
				  populateGEOs(cityId);
				 }
			
			 if(!app.geos.districts.containsKey(lastGeo.getDistrict()))*/{
				  GEO_bean gb = new GEO_bean();
				  gb.setGeoType(QiYouConstant.GEO_DISTRICT);
				  gb.setName(GEOadress.district);
				  gb.setParentId(cityId); 
				 
				  districtId =addNewGeos(gb);	
				  app.geos.streets.clear();
				  app.geos.GEOstreets.clear();
				  app.geos.streetNos.clear();
				  app.geos.GEOstreetNos.clear();
			 }
			   
		 }else{
			 districtId =app.geos.districts.get(GEOadress.district);
			 if(app.geos.GEOstreets.size()==0 
					 || app.geos.GEOstreets.size()>0 
					 && app.geos.GEOstreets.get(app.geos.streets.keySet().toArray()[0].toString()).getParentId()!=districtId ){				
				 app.geos.GEOstreets.clear();
				 app.geos.streets.clear();
				 populateGEOs(districtId);
 				//     QLog.getLogger().d(dTAG, TAG+ " Populate district "+ GEOadress.district);
			 }
			 
		 }
		 
		 if(TextUtils.isEmpty(GEOadress.street )){
			 return geoId;
		 }
		 
		 if( !app.geos.streets.containsKey(GEOadress.street)){
			 /* if(districtId ==0){
				  if(lastGeo.getDistrict()==null)return;
				  districtId =app.geos.districts.get(lastGeo.getDistrict()); 
			  }
			  if(!app.geos.GEOdistricts.get(lastGeo.getDistrict()).getName().equalsIgnoreCase(lastGeo.getDistrict())){
				  app.geos.streets.clear();
				  populateGEOs(districtId);
				 }
			 
			  if(!app.geos.streets.containsKey(lastGeo.getStreet()))*/{
				  GEO_bean gb = new GEO_bean();
				  gb.setGeoType(QiYouConstant.GEO_STREET);
				  gb.setName(GEOadress.street);  
				  gb.setParentId(districtId); 
				  streetId =addNewGeos(gb); 
				  app.geos.streetNos.clear();
				  app.geos.GEOstreetNos.clear();
			  }
		 }else{
			 streetId =app.geos.streets.get(GEOadress.street);
			 if(app.geos.GEOstreetNos.size()==0 
					 || app.geos.GEOstreetNos.size()>0 
					 && app.geos.GEOstreetNos.get(app.geos.streetNos.keySet().toArray()[0].toString()).getParentId()!=streetId ){				
				 app.geos.GEOstreetNos.clear();
				 app.geos.streetNos.clear();
				 populateGEOs(streetId);
//				//     QLog.getLogger().d(dTAG, TAG+ " Populate street "+ GEOadress.street);
			 }
			 
		 } 
		 if(TextUtils.isEmpty(GEOadress.streetNumber)){
			 return geoId;
		 }
		 
		 if(!app.geos.streetNos.containsKey(GEOadress.streetNumber)){
			/* if(streetId ==0){
				 if(lastGeo.getStreet()==null)return;
				 streetId =app.geos.streets.get(lastGeo.getStreet());  
			  }
			 if(!app.geos.GEOstreets.get(lastGeo.getStreet()).getName().equalsIgnoreCase(lastGeo.getStreet())){
				 app.geos.streetNos.clear();
			 	 populateGEOs(streetId);
			 }
				 
			 if(!app.geos.streetNos.containsKey(lastGeo.getStreetNo()))*/{
				 GEO_bean gb = new GEO_bean();
				  gb.setGeoType(QiYouConstant.GEO_STREETNO);
				  if(addressResult!=null && addressResult.getPoiList().size()>0 && addressResult.getPoiList().get(0)!=null){
					   gb.setName(addressResult.getPoiList().get(0).name);
				   }
//				  gb.setName(GEOadress.streetNumber); 	
				  gb.setAddress(GEOadress.streetNumber); 	
				  gb.setParentId(streetId); 
				  gb.setLat(wb.getLatitude());
				  gb.setLon(wb.getLongitude());
				  geoId= addNewGeos(gb);  
				  
			 }
		 }else
			 geoId =app.geos.streetNos.get(GEOadress.streetNumber);
		 
		 
		 return geoId;
	 }
	 
	 void addNewTrackGeo(int geoId,int trackId,int type,long time){
		 
		 if(geoId ==-1) return;
		 ContentValues  values = new ContentValues();     	
		  values.put(TrackProvider.KEY_TRACK_GEO_GID, geoId); 
		  values.put(TrackProvider.KEY_TRACK_GEO_TID, trackId);
		  values.put(TrackProvider.KEY_TRACK_GEO_TYPE,type);
		  values.put(TrackProvider.KEY_TRACK_GEO_TIME,time); 
		  values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis());
		 
		    try {   
		    	       contentResolver.insert(TrackProvider.TRACK_GEOS_URI, values);	 //TODO: remove the try/catch 
		    	         QLog.getLogger().d(dTAG,TAG+" "+ "Added new track-geo: " + trackId+"-"+geoId);
		    }
		    catch (Exception er) { 
		      Log.e(dTAG, TAG +" Update db" +TrackProvider.TRACK_GEOS_URI + " Adding/Update failed.");
		      Utils.logStackTrace(er, dTAG);
		    }
		     
	 }
	 
	 
	 int addNewGeos(GEO_bean gb){ 
		 
		 ContentValues  values = new ContentValues();
     	 int id=-1; 
		  values.put(TrackProvider.KEY_GEO_PARENTID, gb.getParentId()); 
		  values.put(TrackProvider.KEY_GEO_NAME, gb.getName());
		  values.put(TrackProvider.KEY_GEO_TYPE, gb.getGeoType());
		  values.put(TrackProvider.KEY_GEO_COMMENT, gb.getComment());
		  values.put(TrackProvider.KEY_GEO_LAT, gb.getLat()); 
		  values.put(TrackProvider.KEY_GEO_LON, gb.getLon()); 
		  values.put(TrackProvider.KEY_GEO_3, gb.getAddress()); 
		  values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis());
		    try {   
		    	  Uri uri =contentResolver.insert(TrackProvider.GEOS_URI, values); 	 		  
		    	  if(uri !=null) { 
	    		    id = Integer.valueOf(uri.getPathSegments().get(1)) ;
	    			gb.setId(id);
	    			app.geos.putValues(gb); 
//	    		   //     QLog.getLogger().d(dTAG,TAG+" "+ "Added new geo with ID " + uri.getPathSegments().get(1)); 
	    		   //     QLog.getLogger().d(dTAG,TAG+" "+ "Added new geo: " + gb.getName());
		    	 } 
		           
		     
		    }
		    catch (Exception er) { 
		      Log.e("Update Tracks db", "Adding/Update failed.");
		      Utils.logStackTrace(er, dTAG);
		    }
		    return id;
	 }
	 
	 
	 
	 void populateGEOs(int parentId){
		 Cursor cursor =getGEOs(parentId);
		  int geoId ;
		  int geoType =0;
		  String value="";
         try {	       
		      if (cursor!=null && cursor.moveToFirst()) {
		    	  int processedCnt=0;
		    	  while(processedCnt<cursor.getCount()){
			    	  geoId =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID));
	   		     	  geoType =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_GEO_TYPE));
	   		          value =  cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_GEO_NAME));
	   			      app.geos.putValues(new GEO_bean(geoId,parentId, geoType,value,""));
	   			   processedCnt++;
	   			   cursor.moveToNext();
		    	  }
		      } 
		      }catch(Exception er)
		      {
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		    	  if (cursor!=null) cursor.close();
		      }
				     
	 }
	 Cursor	getGEOs(int parentId){
			projection = new String[] { TrackProvider.KEY_ID,TrackProvider.KEY_GEO_NAME,
					TrackProvider.KEY_GEO_PARENTID,TrackProvider.KEY_GEO_TYPE,TrackProvider.KEY_GEO_COMMENT
			}; 
			
	// 	  String where ="ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",-1)" + " <> '" + QiYouConstant.GEO_STREETNO + "'";//TODO: when data is big, use the filter.
	// 	 String where ="ifnull(" + TrackProvider.KEY_GEO_PARENTID +",-1)" + " = '" + parentId + "'";//TODO: when data is big, use the filter.
	 	  String where = TrackProvider.KEY_GEO_PARENTID + " = '" + parentId + "'";  //TODO: use selection args
	 	  return contentResolver.query(TrackProvider.GEOS_URI, projection, where, null, null); 
	     
 }


	 Cursor	getWps(){
			projection = new String[] { TrackProvider.KEY_ID,
							          TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP, 
								      TrackProvider.KEY_TRACK_ROAD_BEARS,TrackProvider.KEY_TRACK_MAXRD_WP ,TrackProvider.KEY_TRACK_TYPE
								      ,TrackProvider.KEY_TRACK_CREATOR
				   					};
				
//				 Uri uri = Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId));
				 Uri uri =TrackProvider.TRACKS_URI;//Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId));
//				 String where ="ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 
//						 		+" and "+  TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt();
				 String where ="1=1 " ;//+  TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt();
				 
				 where += " and "+  TrackProvider.KEY_TRACK_TYPE +"!=" +TrackType.GPX.toInt(); //not include gpx				 
				 
				 if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) {
					 where +=" and ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 ;
				 	  where+=whereUserId;
				 }
//				  where += " and "+ TrackProvider.KEY_ID +" =1";
				
 			     QLog.getLogger().d(dTAG, TAG+" get wps where is: "+ where);
				 return contentResolver.query(uri, projection, where, null, null);
			     
			 
		}
	 
	 Cursor	getWps4gpx(){
			projection = new String[] { TrackProvider.KEY_ID,
										TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP, 
									    TrackProvider.KEY_TRACK_MAXRD_WP 
				   					};
				
//				 Uri uri = Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId));
				 Uri uri =TrackProvider.TRACKS_URI;//Uri.withAppendedPath(TrackProvider.CONTENT_URI, String.valueOf(trackId));
//				 String where ="ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 
//					 		+" and "+  TrackProvider.KEY_TRACK_TYPE +"=" +TrackType.GPX.toInt();
//				
//				 if(QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) where =null;
				 
				 
				 String where =  TrackProvider.KEY_TRACK_TYPE +"=" +TrackType.GPX.toInt();
					
				 if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK) 
					 where +=" and ifnull(" + TrackProvider.KEY_TRACK_GEO_STATUS +",1)" + " > " + 0 ;
				 
				 where+=whereUserId;
			     
				 return contentResolver.query(uri, projection, where, null, null);
			     
			 
		}
	 
	 
	 void genStaticMap4gpx(){
		 Cursor cursor =getWps4gpx();
         try {	       
      	  //     QLog.getLogger().d(dTAG, TAG+" 共"+cursor.getCount() +" 条gpx track记录需要更新。" );
      		for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
      			
	    		  networkErrors=0;
	    		  geoCnt=0;
	    		  trackId =cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)); 
	    		  track = new Track();
	    		  track.getTrackBean().setTrackId(trackId); 
	    		  
   			      if(!QiYouConstant.PROCESS_ALLTRACK_GEO_FOOTMARK && track.isStaticMapExist()) return; 
   			          // QLog.getLogger().d(dTAG, TAG+" start get staticMap of track "+trackId );	  
//   			       track.getTrackBean().setTrackId(trackId);
//   			       track =new Track(null,cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT)),null, null);
   			     
   			      track =new Track(trackId,true,null, null);
   			      
   			      track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP)));
   			      track.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP)));
//   			      track.setMaxDistWp(new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP))));
   			      track.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP)));
   			      track.getTrackBean().setType(TrackType.GPX);
   			      generateStaticMap(track);
		    	  
		      } 
		      }catch(Exception er)
		      {
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		       if(cursor!=null) cursor.close();
		      }
         
	 }
	/* 
	 void buildPathPoints(ArrayList<Waypoint_bean> wps){
		    Waypoint_bean wb;
//		    Waypoint_bean lastWb = null;
		    Waypoint_bean lastWb4map = null; 
	        final int MAXLATLNGS=50-3; 
	        trackDist =track.getLastWp().getWb().getSumDist();
		     float stepValue =wps.size()>MAXLATLNGS &&trackDist>0 ?trackDist/MAXLATLNGS:0;  
		     pathPoints="";
		     float skipDist=0;
//		     float skiptDist=0;
//		    //     QLog.getLogger().d(dTAG, TAG+" wps.size() is " + wps.size() +"----------------------------");
//		    //     QLog.getLogger().d(dTAG, TAG+" MAXLATLNGS is " + MAXLATLNGS );
//		    //     QLog.getLogger().d(dTAG, TAG+" trackDist/MAXLATLNGS " + trackDist/MAXLATLNGS );
//		     
//		    //     QLog.getLogger().d(dTAG, TAG+" stepValue is " + stepValue);
		     
			 for(int i=0;i<wps.size();i++) {
			    	  
					 wb = wps.get(i);
					 
					 if(wb==null)continue;
//					 lastWb	=lastWb==null?wb:lastWb;				 
//					 if(trackId==34)
					 {
						 
//						//     QLog.getLogger().d(dTAG, TAG+" No.i,wb.gettime():"+i+"," + Utils.getFormatedTime(wb.getTime()));
					 }
					 lastWb4map=lastWb4map==null?wb:lastWb4map;
//					 if (TextUtils.isEmpty(pathPoints)||wb.getTime()>lastWb4map.getTime())  
//						//     QLog.getLogger().d(dTAG, TAG+" No.i,lastwb.gettime():"+i+"," + Utils.getFormatedTime(lastWb4map.getTime()));
//						//     QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()" + (wb.getSumDist()-lastWb.getSumDist()));
//						//     QLog.getLogger().d(dTAG, TAG+" skipDist" + skipDist);
//						//     QLog.getLogger().d(dTAG, TAG+" wb.getSumDist()-lastWb.getSumDist()+skipDist" + (wb.getSumDist()-lastWb.getSumDist()+skipDist));
						 float f =wb.getSumDist()-lastWb4map.getSumDist()+skipDist;
//						//     QLog.getLogger().d(dTAG, TAG+" current dist " + f +", stepvalue is "+ stepValue +" dist >stepvalue?"+(f>=stepValue));
						 if(TextUtils.isEmpty(pathPoints)||f>=stepValue 
								 ||wb.getTime()==track.getStartWp().getWb().getTime()
								 ||wb.getTime()==track.getLastWp().getWb().getTime()
								 ||wb.getTime()==track.getMaxDistWp().getWb().getTime()){  
							 
							  pathPoints=pathPoints+Utils.getbdLon(wb.getLatitude(), wb.getLongitude())+","+Utils.getbdLat(wb.getLatitude(), wb.getLongitude())+";";
							  skipDist=0; 
						 }
						 else
							 skipDist +=wb.getSumDist()-lastWb4map.getSumDist();
						 
						 lastWb4map =wb;
					  
//						lastWb=wb;
					 if(wb.getTime()<lastWb4map.getTime())continue;
					  
					 
//					  wb.setBearDist(wb.getBearDist()+skiptDist);  //丢弃重复geo点
//					   skiptDist=0;
					   
			 }
	 }
	 */
	 
	 
	
	 
	 
	 boolean generateStaticMap(Track track)  {
		 
//		 if(track.getTrackBean().getType()!=TrackType.GPX)return true;
	/*	 
		 pathPoints= Utils.buildPathPoints(track.getTrackBean().getType()==TrackType.GPX?track.getTrackBean().getTrkseg():track.getTrackBean().getRoadWps()
				 ,track
				 ,true
				 ,50-3); 
		 
		if(TextUtils.isEmpty(pathPoints))return false;*/
		
		
		/*
		http://api.map.baidu.com/staticimage?center=116.403874,39.914888&width=500&height=500&zoom=11&
		paths=116.288891,40.004261;116.487812,40.017524;116.525756,39.967111;116.536105,39.872373|116.442968,39.797022;116.270494,39.851993;116.275093,39.935251;116.383177,39.923743
		&pathStyles=0xff0000,5,1
		 *  
		 */
		
		
		
//		staticMapUrl =baiduUrl+String.format(format, width,height,pathPoints,pathStyle);
 
		
//		String staticMapUrl =Utils.getBaiduStaticMapUrl(track);
	
		try {
//			response = app.getHttpClient().execute(httpget);
			
 			// QLog.getLogger().d(dTAG, TAG+"response.getStatusLine().getStatusCode():" +response.getStatusLine().getStatusCode());
		
			
			File dir = new File(track. getStaticMapPath());
			
			if(!dir.exists())dir.mkdirs();
		 
//			String fileName=track.getStaticMap();
			String fileName =track.getStaticMapPath() + track.getStaticMapUrl().hashCode()+".png" ; 
			
			File pic = new File(fileName);
			if(pic.exists() && !isSpecifiedTrackMap){ 
				return true;
			}
//			os = new FileOutputStream(track.getStaticMap()); 
			
			String staticMapUrl =track.getStaticMapUrl();
	 		// QLog.getLogger().d(dTAG, TAG+" staticMapUrl is"+staticMapUrl);
			if(TextUtils.isEmpty(staticMapUrl))return false;
		    HttpResponse response= app.httpsExecute(staticMapUrl);
			OutputStream os;
			if(response==null ||response.getStatusLine()==null||response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK) return false; 
			
			os = new FileOutputStream(fileName); 
			
			response.getEntity().writeTo(os);
			// QLog.getLogger().d(dTAG, TAG+" new pic of fileName :" + fileName);
//			CopyStream(is, os);
			os.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	  return true;
		  
	 }
	  
		/*
		 	The Google Elevation API
		 */
		
		
		
		private void updateEles(){
			
		} 
		
		
		 
	 
	 @Override
	public void onDestroy() {
			// QLog.getLogger().d(dTAG, TAG+" service destroy.....");
//		    app.isProcessingGEO =false;
		    
			super.onDestroy();

		}
	@Override
	public void onGetGeoCodeResult(GeoCodeResult arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
	
		GEOadress = result.getAddressDetail();		
		 
		addressResult =result;
		
//		QLog.getLogger().d(dTAG,TAG+" ----------------- onGetReverseGeoCodeResult  "  + result.getAddress());
		
	}
	 
	public boolean getBdGEOadress(double lat, double lon){
		
 		  
		if(mSearch ==null){
	  	   mSearch= GeoCoder.newInstance();
	  	   mSearch.setOnGetGeoCodeResultListener(this);
	     }
		 
		  GEOadress=null;
//		  isGEOerror=false;
//		 double blat = Utils.getbdLat(lat,  lon);
//	     double blon = Utils.getbdLon(lat,  lon);  
//	    LatLng ptCenter = new LatLng( lat,  lon) ;
	    LatLng ptCenter = new LatLng(Utils.getbdLat(lat,  lon), Utils.getbdLon(lat,  lon));
	    isGEOerror = !mSearch.reverseGeoCode(new ReverseGeoCodeOption() .location(ptCenter));
//	    return mSearch.reverseGeoCode(new ReverseGeoCodeOption() .location(ptCenter));
	    
	    return isGEOerror;
	    
	 
//		 QLog.getLogger().d(dTAG,TAG+" mSearch started " +System.currentTimeMillis());
//		QLog.getLogger().d(dTAG,TAG+String.format(" lat %s,lon %s,GEOadress==null?%s,isGEOerror?%s", lat,lon, GEOadress==null, isGEOerror));

//		 QLog.getLogger().d(dTAG,TAG+" mSearch.reverseGeocode: " +result);
		 
	}  
	  AddressComponent  GEOadress;
	  ReverseGeoCodeResult addressResult;
	  boolean isGEOerror;
	}   
 
