/**
 * 
 */
package com.qiyou.mb.android.beans;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import org.alternativevision.gpx.beans.GPX;

import android.location.Location;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.basic.GEOaddress;
import com.qiyou.mb.android.beans.basic.Media;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.mediaStatus;
import com.qiyou.mb.android.utils.enums.mediaType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;
//import org.alternativevision.gpx.GPXParser;
//import com.baidu.a.a.a.a;
 
/**
 * @author mwang
 *
 *一次骑行/运动记录
 */
public class Track {
    public static String TAG ="com.qiyou.beans.Track";
    public static String dTAG ="com.qiyou";
	private Track_bean tb;
	private Waypoint _lastWp;  
	private Waypoint _startWp;  
	private String _lastWpJson;
	private String _startWpJson;	
	private StringBuffer wpsJson ; //wps 原始 Json ;和数据库里保存的track content字段内容一致.	
//	private Waypoint _lastRoadBear;	
	private String _lastRbJson="";
	private StringBuffer _roadBook = new StringBuffer();
	private StringBuffer _rdWpsJson = new StringBuffer();
	private StringBuffer _mdWpsJson = new StringBuffer();
//	public ArrayList<Waypoint_bean> roadWps = new ArrayList<Waypoint_bean>();	
	private String _maxDistWpJson; 
	private Waypoint _maxDistWp; 
	private double maxR;	
	public StringBuffer newMdWpsJson = new StringBuffer();
	
	public Track()
	{
		tb = new Track_bean();
		tb.setUserid(QiYouConstant.PV_USER_ID);
	}
	
	public Track(String jsonTrack){
		Gson gson = new Gson();		
		try{
			tb = gson.fromJson(jsonTrack, Track_bean.class);
			}catch(Exception e)
			{				
				Utils.logStackTrace(e, dTAG);
			} 
	}
	public Track(Track_bean track_bean)
	  {
	    if (track_bean == null)
	    {
	      this.tb = new Track_bean();
	      this.tb.setUserid(QiYouConstant.PV_USER_ID); 
	      return;
	    }
	     
	      this.tb = track_bean;
	      this._startWp = this.tb.getStartWp();
	      this._lastWp = this.tb.getLastWp();
	      this._maxDistWp = this.tb.getMaxDistWp();
	 	  
//			 QLog.getLogger().d(dTAG, "  mtrack_bean startwp: "+mTrack_bean.getStartWp().toString());
//			 QLog.getLogger().d(dTAG, "  mtrack_bean endwp: "+mTrack_bean.getLastWp().toString());
//			 QLog.getLogger().d(dTAG, "  mtrack_bean endwp: "+mTrack_bean.getLastWp().toString());
//			getTrackBean().getTrkseg().clear();
//			 QLog.getLogger().d(dTAG, "  loaded track is"+this.toGsonString());
			 
		 
	  }
//	public Track(GPX gpx){
//		pareseGpx( gpx);
//	}
	
	public Track(int trackId, boolean isAssembleContent,String rdWpsJson,String mdWpsJson){
		 getTrackBean().setTrackId(trackId);
		if(isAssembleContent)
			assemblyContent(); 
		 if(TextUtils.isEmpty(rdWpsJson)){
			 assemblyBearContent();
		 }		 
		 pareseTrack(null,   null,  rdWpsJson,  mdWpsJson);
		
	}
	
	public Track(int trackId,String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){
		 getTrackBean().setTrackId(trackId);
		 if(TextUtils.isEmpty(rdWpsJson)){
			 assemblyBearContent();
		 }
		 pareseTrack(jsonTrack,   jsonWps,  rdWpsJson,  mdWpsJson);
		
	}
	/*
	 * jsonTrack can be null
	 */
	public Track(String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){
	
		pareseTrack(jsonTrack,   jsonWps,  rdWpsJson,  mdWpsJson);
		
	}
	
	void pareseTrack(String jsonTrack, String jsonWps,String rdWpsJson,String mdWpsJson){
		Gson gson = new Gson();		
		try{
			if(!TextUtils.isEmpty(jsonTrack)){
				tb = gson.fromJson(jsonTrack, Track_bean.class);
				return;
			}
			else getTrackBean();//tb = new Track_bean();
			String json="";
			//检查 json 格式,应该为[{...},{...}]格式
//			wpsJson = new StringBuffer();
//			wpsJson.append(jsonWps);  //put it before convert to wps, in case failed, then recovery track will miss existed wps in db.
		 	if(!TextUtils.isEmpty(jsonWps)){	
//				json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");		
				json=getCleanJson(jsonWps);
				 
				wpsJson = new StringBuffer();
				wpsJson.append(json);  //put it before convert to wps, in case failed, then recovery track will miss existed wps in db.
	//			tb.setTrksegs(wps);	
				if(!json.startsWith("["))
					json ="["+json ; 
				if(!json.endsWith("]")){
					json =json+"]";
				}
				tb.setTrksegs(getWPS(gson,json));
				wpsJson=new StringBuffer();  //TODO check if it will cause :     //put it before convert to wps, in case failed, then recovery track will miss existed wps in db.
			} 
			if(!TextUtils.isEmpty(rdWpsJson)){
//				json= rdWpsJson.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");;	
				json=getCleanJson(rdWpsJson);
//				json= rdWpsJson.replace(" ","");	
				if(!json.startsWith("["))
					json ="["+json ; 
				if(!json.endsWith("]")){
					json =json+"]";
				}
//				roadWps =getWPS(gson,jsonWps);
				tb.setRoadWps(getWPS(gson,json));
			}
			if(!TextUtils.isEmpty(mdWpsJson) && mdWpsJson.length()>1){
//				_mdWpsJson.append(mdWpsJson);
//				json= mdWpsJson.replace("[","").replace("]", "").replace(" ","");		
				json= mdWpsJson.replace(" ","").replace("}{", "},{").replace("null", "").replace("}]{" ,"},{").replace("[]" ,""); 
				if(!json.startsWith("["))
					json ="["+json ; 
				if(!json.endsWith("]")){
					json =json+"]";
				}
//				QLog.getLogger().d(dTAG, TAG+" setMdWps: "+  tb.getTrackId() +", track status is" +tb.getStatus());
				tb.setMdWps(getWPS(gson,json));
			}
			
			
			
			
			//wpsJson 初始化,为继续采集/更新gps位置信息(wps)做准备.
//			wpsJson = new StringBuffer();
//			wpsJson.append(jsonWps);
			}catch(Exception e)
			{
				Utils.logStackTrace(e, dTAG);
				if(!TextUtils.isEmpty(jsonTrack)){
					Log.e(dTAG,TAG + "  Json to track error--------------as below jsonTrack----" );
					Log.e(dTAG ,TAG+ jsonTrack );
				}
				if(!TextUtils.isEmpty(jsonWps)){
					Log.e(dTAG ,TAG+"below is wps jsonWps---------------");
					Log.e(dTAG ,TAG+ jsonWps );
				}
				
				
			}
	}

	String getCleanJson(String json){
		
 				json = json.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");
//		        json = json.replace(" ","").replace("}{", "},{").replace("null", "");
//				json ="["+json+"]"; 
				return json;
	}
	/*CopyOnWriteArrayList<Waypoint_bean> getWPS(Gson gson, String jsonWps) throws Exception{
		CopyOnWriteArrayList<Waypoint_bean> wps = new CopyOnWriteArrayList<Waypoint_bean>();  
			try{
		 	      Type type = new TypeToken<CopyOnWriteArrayList<Waypoint_bean>>(){}.getType(); 
				  wps =  gson.fromJson(jsonWps,type);
			}catch(Exception e)
			{
				//throw e;
				Log.e(dTAG,TAG+"Track "+ tb.getTrackId() +" getWPS error:  "+ jsonWps);
				wps =buildWps(jsonWps);
				
			}
//			dwps =buildWps(jsonWps);
			return wps;
		
			
	}*/
	
	 ArrayList<Waypoint_bean> getWPS(Gson gson, String jsonWps) throws Exception{
		 ArrayList<Waypoint_bean> wps = new  ArrayList<Waypoint_bean>();  
			try{
		 	      Type type = new TypeToken< ArrayList<Waypoint_bean>>(){}.getType(); 
				  wps =  gson.fromJson(jsonWps,type);
			}catch(Exception e)
			{
				//throw e;
				Log.e(dTAG,TAG+"Track "+ tb.getTrackId() +" getWPS error:  "+ jsonWps);
				wps =buildWps(jsonWps);
				
			}
//			dwps =buildWps(jsonWps);
			return wps;
		
			
	}
	  
	/*CopyOnWriteArrayList<Waypoint_bean>  buildWps(String jsonWps) {
		  
		CopyOnWriteArrayList<Waypoint_bean> wps = new CopyOnWriteArrayList<Waypoint_bean>();  		  
//		  jsonWps= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{");
		  jsonWps= jsonWps.replace(" ","").replace("}{", "},{");	
		  String[] wpsS = jsonWps.split("\\}\\,\\{");
		  String tmp = null;
		  for(String json : wpsS){
			  tmp = json;
			  json =json.endsWith("}")?json: json.endsWith("},")?json:json+"}";			 
			  json =json.startsWith("[")?json.substring(1,json.length()):json.endsWith("]") ?json.substring(0,json.length()-1):json;
			  json =json.startsWith("{")?json:json.startsWith(",{")?json:"{"+json;
			  try{ 
//				  tmp = json;
				  wps.add( new Waypoint(json).getWb());
			  }
			  catch (Exception e){
				  Log.e(dTAG,TAG+ " buildWps error for json:  "+ tmp);
				  Log.e(dTAG,TAG+ " Track "+ tb.getTrackId() +"  buildWps error:  "+ json);
				  Utils.logStackTrace(e, TAG);
					Log.e(dTAG,e.getLocalizedMessage());
			  }
			  
		  }
		  return wps;
	  }*/
	  
	 
	 ArrayList<Waypoint_bean>  buildWps(String jsonWps) {
		  
			 ArrayList<Waypoint_bean> wps = new  ArrayList<Waypoint_bean>();  		  
//			  jsonWps= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{");
			  jsonWps= jsonWps.replace(" ","").replace("}{", "},{");	
			  String[] wpsS = jsonWps.split("\\}\\,\\{");
			  String tmp = null;
			  for(String json : wpsS){
				  tmp = json;
				  json =json.endsWith("}")?json: json.endsWith("},")?json:json+"}";			 
				  json =json.startsWith("[")?json.substring(1,json.length()):json.endsWith("]") ?json.substring(0,json.length()-1):json;
				  json =json.startsWith("{")?json:json.startsWith(",{")?json:"{"+json;
				  try{ 
//					  tmp = json;
					  wps.add( new Waypoint(json).getWb());
				  }
				  catch (Exception e){
					  Log.e(dTAG,TAG+ " buildWps error for json:  "+ tmp);
					  Log.e(dTAG,TAG+ " Track "+ tb.getTrackId() +"  buildWps error:  "+ json);
					  Utils.logStackTrace(e, TAG);
						Log.e(dTAG,e.getLocalizedMessage());
				  }
				  
			  }
			  return wps;
		  }
	 
	  
	  public static Track newInstance(String gpxFile){
//		  GPX gpx=Utils.pareseGpx(gpxFile);		  
//		Track tr =  new Track(Utils.pareseGpx(gpxFile));
//		tr.getTrackBean().setSrc(gpxFile);
		
		Track tr = new Track(); 
		/*if(tr.pareseGpx(gpx)){
			tr.getTrackBean().setSrc(gpxFile);
			return tr;
		}else return null;*/
		if(tr.pareseGpx(gpxFile)){ 
			return tr;
		}else return null;
		 
	  }
	  public boolean pareseGpx(String gpxFileName){
//	  public boolean pareseGpx(GPX gpx){
			try{
				
				long t1 =System.currentTimeMillis();
				
				 GPX gpx=Utils.pareseGpx(gpxFileName);	 
				long t2 =System.currentTimeMillis();
				// QLog.getLogger().d(dTAG, "pares gpx time 1: "+ Utils.getTimeCnt(t2-t1, true));
				if(gpx==null)return false;
				org.alternativevision.gpx.beans.Track gpxTr = null;
				while(gpx.getTracks().iterator().hasNext()){
					gpxTr =gpx.getTracks().iterator().next();
					if(gpxTr!=null)
						break; //support only one track,currently.
				}
				if(gpxTr==null)return false;
				
				
				tb =new Track_bean();
				tb.setCreator(gpx.getCreator());//gpx.getCreator());
			    tb.setCreatTime(System.currentTimeMillis());
				tb.setName(gpxTr.getName());
				tb.setComment(gpxTr.getComment());
				tb.setDescription(gpxTr.getDescription());
				tb.setType(TrackType.GPX);
				tb.setSrc(gpxFileName);
				long t3 =System.currentTimeMillis();
				// QLog.getLogger().d(dTAG, "pares gpx time 2: "+ Utils.getTimeCnt(t3-t2, true));
				ArrayList<org.alternativevision.gpx.beans.Waypoint> gpxWps = gpxTr.getTrackPoints();
				Waypoint lastwp=null;
				float dist=0f;
				long sumdist=0;
				float eDist=0f;	 
				final float avSpeed=20f/3600f;//米/毫秒
				long lasttime=0;
				for(org.alternativevision.gpx.beans.Waypoint gpxWp:gpxWps){
					Waypoint wp = new Waypoint();
					
					wp.getWb().setDesc(gpxWp.getDescription());
					if(gpxWp.getLatitude()!=null)
						wp.getWb().setLatitude( (gpxWp.getLatitude().floatValue()));
					if(gpxWp.getLongitude()!=null)
						wp.getWb().setLongitude( (gpxWp.getLongitude().floatValue()));
					wp.getWb().setComment(gpxWp.getComment());
					if(gpxWp.getElevation()!=null)
						wp.getWb().setElevation(gpxWp.getElevation().floatValue());
					if(gpxWp.getSpeed()!=null)
						wp.getWb().setSpeed(gpxWp.getSpeed().floatValue()*3.6f);  
					if(gpxWp.getTime()!=null){
						if(gpxWp.getTime().getTime()>0)
							wp.getWb().setTime(gpxWp.getTime().getTime());
						else{
							
 							long time_interval =(long)(dist/avSpeed);
 							// QLog.getLogger().d(dTAG,TAG+" interval is "+time_interval);
 							lasttime=lasttime>0?lasttime:System.currentTimeMillis();
							wp.getWb().setTime(lasttime+time_interval);
						}
					}
					
					if(lastwp!=null){ 
						dist =(float) Utils.getDistanceFromXtoY(wp.getWb().getLatitude(), wp.getWb().getLongitude(), lastwp.getWb().getLatitude(), lastwp.getWb().getLongitude());
				 		sumdist+=dist; 
						eDist=wp.getWb().getElevation()-lastwp.getWb().getElevation(); 
						lasttime=wp.getWb().getTime();
					}
					
					wp.getWb().setDistance(dist);
					wp.getWb().setSumDist(sumdist);
					wp.getWb().setEled(eDist);
					
					String gPics=gpxWp.getPics();
					if(!TextUtils.isEmpty(gPics)){
						String gpxPath=gpxFileName.substring(0,gpxFileName.lastIndexOf("/")+1);
					 
						String[] pics; 
						if(gPics.contains(","))
							pics = gPics.split(",");
						else if(gPics.contains(";")){
							pics = gPics.split(";"); 
						}else  
							pics = gPics.split(","); 
						
						if(pics!=null && pics.length>0){
							for(String url :pics){
								this.setMd(gpxPath+url, null, mediaType.PIC);
								// QLog.getLogger().d(dTAG,TAG+" added PIC to gpxTrack \n "+ gpxPath+url);
							}
						}
					} 
					setLastWp( wp);
					
					/*_lastWpJson=wp.toJsonWp();
					if( setLastWp( wp) ){ 		 
						if (TextUtils.isEmpty(_startWpJson ) || wpsJson ==null){
								_startWpJson = _lastWpJson;
								wpsJson = new StringBuffer();			
							}
						
						wpsJson.append(_lastWpJson); 
						wpsJson.append(",");
					}*/
						
					lastwp =wp;
				}
				
				
				getJsonWps().append(wps2json(tb.getTrkseg()));
				
				long t4 =System.currentTimeMillis();
				// QLog.getLogger().d(dTAG, "pares gpx time 3: "+ Utils.getTimeCnt(t4-t3, true));
				if(_maxDistWp!=null){
			    	_maxDistWp.getWb().setTurnFlag(wpFlag.MAXR);
			    	setLastRoadBear(_maxDistWp); 
			    	// QLog.getLogger().d(dTAG,TAG+" set marR WP to the roadbear \n "+ _maxDistWp.toString());
			    }
			    
			    if(_lastWp!=null){
			    	_lastWp.getWb().setTurnFlag(wpFlag.END);
			    	setLastRoadBear(_lastWp);
			    	// QLog.getLogger().d(dTAG,TAG+" set last WP to the roadbear \n "+ _lastWp.toString());
			    }
			     setBearWps(tb.getRoadWps()); 
			     
			     long t5 =System.currentTimeMillis();
			     
			     // QLog.getLogger().d(dTAG, "pares gpx time 4: "+ Utils.getTimeCnt(t5-t4, true));
			}catch(Exception e)
			{				
				Utils.logStackTrace(e, dTAG);
				return false;
			} 
			return true;
		}
	  
	  public boolean mergeTrack(int trackId){
		  
		  
		  Utils.getContentPah(trackId);
		  StringBuffer wpsJson;
				if(trackId<=0)
					return false;
				else{
					wpsJson=new StringBuffer();
					try { 
						
						wpsJson.append(Utils.readSDFile(getContentPah()));
					} catch (IOException e) {
						Utils.logStackTrace(e, TAG);
					}
				}
				 
				String json=wpsJson.toString();
//				CopyOnWriteArrayList<Waypoint_bean> inWps = null;
				 ArrayList<Waypoint_bean> inWps = null;
				if(!TextUtils.isEmpty(json)){	
					json=getCleanJson(json); 
					if(!json.startsWith("["))
						json ="["+json ; 
					if(!json.endsWith("]")){
						json =json+"]";
					}
					try {
						inWps = getWPS( new Gson(),json);
					} catch (Exception e) {				
						Utils.logStackTrace(e, dTAG);
						if(!TextUtils.isEmpty(json)){
							Log.e(dTAG ,TAG+" below is wps jsonWps---------------");
							Log.e(dTAG ,TAG+ json );
						}
					}
				}
				
				Waypoint wp;
				float oDist=tb.getDistance();
				for(Waypoint_bean wb:inWps){
					wb.setSumDist(wb.getSumDist()+oDist);
					wp=new Waypoint();
					wp.setWb(wb);					 
					this.setLastWp(wp);
					wpsJson.append(wp.toString()); 
					wpsJson.append(",");
				}
		 
//				return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+".txt";
				 
			 
		  
		  
		  return true;
	  }
	  
  public boolean mergeTrack(Track mTrack){ 
		  if(mTrack==null)return false;  
				
				Waypoint wp;
				float oDist=tb.getDistance();
				for(Waypoint_bean wb:mTrack.getTrackBean().getTrkseg()){
					wb.setSumDist(wb.getSumDist()+oDist);
					wp=new Waypoint();
					wp.setWb(wb);					 
					this.setLastWp(wp); 
				} 
 				wpsJson.append(mTrack.getJsonWps());    
		  return true;
	  }
		
		
	/**
	 * @return the tb
	 */ 
	public Track_bean getTrackBean() {
		if(tb ==null) tb = new Track_bean();
		return tb;
	}

	 /**
	 * @param tb the tb to set
	 */ 
	public void setTrackBean(Track_bean tb) {
		this.tb = tb;
	} 
	
	 /*
	 * return string generated by Gson for the referenced track_bean
	 */
	public String toGsonString()
	{
//		long bfdbTime = System.currentTimeMillis();	  
		String strwb ="";
	//	if(null != tb.getNumber())		 
		{		 
			Gson gson = new Gson();	
			try{
			strwb = gson.toJson(tb);
		/*	if(QiYouConstant.DEVELOPER_MODE)
	    	{ 
				 QLog.getLogger().d(dTAG ,TAG+" 准备 track to json 耗时: " +String.valueOf((System.currentTimeMillis()-bfdbTime)) + "毫秒");
	        	   	
	    	}*/
			}catch(Exception e)
			{
				
				Utils.logStackTrace(e, dTAG);
			}
			
		}
	//	Log.e(TAG,strwb);
		return strwb;
	}
	
	/**
	 * Returns a JSON String representation of referenced track_bean.
	 */	
	@Override
	public String toString() {
		return toGsonString();
		/*StringBuffer sb = new StringBuffer();	 
		sb.append("{");	
		sb.append("name:"+tb.getName()+",");
		sb.append("cmt:" + tb.getComment() + ",");
		sb.append("desc"+tb.getDescription() + ",");
		sb.append("src:"+tb.getSrc() +",");
		sb.append("number:"+tb.getNumber()+ ",");
		sb.append("type:"+tb.getType()+ ",");		
		sb.append("trkseg:");
		sb.append("[");
		ArrayList<Waypoint> wplst =tb.getTrkseg();
		if(null !=wplst )
		for(Waypoint wp:wplst)
		{
			sb.append(wp.toString());
		}
		sb.append("]");
		sb.append("}");	
		//return sb.toString();
		*/
		 
	}
	
	public String toGpxString()
	{
		
		
		return null;
	}

	/**
	 * @return the lastWp
	 */
	public Waypoint getLastWp() {
		return _lastWp;
	}
 
 
	
	/**
	 * add new waypoint to the track	 * 
	 * @param lastWp the lastWp to set
	 * 
	 * return false when the wp is null or not a new wp.
	 */
	public boolean setLastWp(Waypoint lastWp) {		
		if(lastWp == null ||lastWp.getWb().getTime()==0)return false;		
	
//		if(lastWp.getWb().getTime()<this.getTrackBean().getStartTime()) return false; //TODO: make it enabled.
		
//		if(_lastWp!=null)				
//				QLog.getLogger().d(dTAG,TAG+" eixist last wp is:" +  _lastWp.toString());
//			else
//				QLog.getLogger().d(dTAG,TAG+" _lastWp is null, the new last wp is:" +  lastWp.toString());
		
		if(null != _lastWp && lastWp.getWb().getTime()< _lastWp.getWb().getTime())
		{
			// QLog.getLogger().d(dTAG, TAG+" lastWp.getWb().getTime() "+lastWp.getWb().getTime() );
			// QLog.getLogger().d(dTAG, TAG+" _lastWp.getWb().getTime() "+_lastWp.getWb().getTime() );
			// QLog.getLogger().d(dTAG, TAG+" new wp is not newer than last wp, return " );
			return false;
			
		}
		
		if(tb.getStartWp() ==null ||_startWp == null){
    		
			_startWp =_startWp==null?lastWp:_startWp;
			if(tb.getStartWp() ==null)tb.setStartWp(_startWp); 
			setLastRoadBear(lastWp);
		 }
		
		
		if(null == _lastWp ||lastWp.getWb().getTime()>_lastWp.getWb().getTime()){// ||QiYouConstant.DEVELOPER_MODE){ 
			_lastWp = lastWp;
			tb.setLastWp(_lastWp);
			tb.getTrkseg().add(_lastWp.getWb()); 
// 		    if(lastWp.getWb().getDistance()>=0)			
// 				  tb.setDistance(tb.getDistance()+lastWp.getWb().getDistance()); //累加总里程, Meter
			
			   if(lastWp.getWb().getSumDist()>tb.getDistance())			
					tb.setDistance(lastWp.getWb().getSumDist()); //累加总里程, Meter
 				
				tb.setPauseTime(tb.getPauseTime()+lastWp.getWb().getPauseTime());//累加暂停时间
//				if(lastWp.getWb().getTime()>tb.getEndTime())
				tb.setEndTime(lastWp.getWb().getTime());//更新 最后一个wp time
	//			tb.setOffTime(tb.getOffTime()+lastWp.getWb().getOfftime()); // track offtime will be handled by force update
				if(lastWp.getWb().getElevation()!=0 && lastWp.getWb().getEled()>0){
					tb.seteUpDist(tb.geteUpDist()+lastWp.getWb().getEled());   //累加累积上升海拔高度
					
				}
				if(lastWp.getWb().getElevation()!=0 && lastWp.getWb().getEled()<0){
					tb.seteDownDist(tb.geteDownDist()+ lastWp.getWb().getEled()) ;//累加累积下降海拔高度
				}
//				if(lastWp.getWb().getSpeed() >tb.getTopSpeed())
				tb.setTopSpeed(lastWp.getWb().getSpeed());	  
	//			if(lastWp.getWb().getRoadBear()!=0)setLastRoadBear(lastWp);
				
//				QLog.getLogger().dLog(dTAG, "set lastwp,lastWp.getWb().getTurnFlag()"+ lastWp.getWb().getTurnFlag());
				if(!tb.getRoadWps().contains(lastWp)
						&& lastWp.getWb().getTurnFlag()!=wpFlag.NORMAL 
						&&lastWp.getWb().getTurnFlag()!=wpFlag.CUST
						&&lastWp.getWb().getTurnFlag()!=wpFlag.TENT
						&&lastWp.getWb().getTurnFlag()!=wpFlag.REST
						)
					setLastRoadBear(lastWp); 
				if(tb.getType()==TrackType.GPX && !TextUtils.isEmpty(lastWp.getWb().getComment())){
					lastWp.getWb().setRoadBook(lastWp.getWb().getComment());
					lastWp.getWb().setComment("");
					tb.getRoadWps().add(lastWp.getWb());
				}
					 
				 maxR=Utils.getDistanceFromXtoY(_lastWp.getWb().getLatitude(), _lastWp.getWb().getLongitude(), _startWp.getWb().getLatitude(), _startWp.getWb().getLongitude());
				if(maxR>tb.getMaxR() && maxR<tb.getDistance()){
					tb.setMaxR((float) maxR);
					tb.setMaxDistWp(_lastWp);
					_maxDistWpJson =_lastWpJson; 
					_maxDistWp =_lastWp;
					 
				}
					
						
				
				
			return true;
		}else 
			if(lastWp.getWb().getMedias().size()>0 && lastWp.getWb().getTime() == _lastWp.getWb().getTime() ){
				_lastWp = lastWp;
			//	wpsJson.replace(wpsJson., end, string)
				_lastWpJson=_lastWp.toString();
				 
				int start = wpsJson.lastIndexOf("},{")+3;
				int end =wpsJson.length();			
				//wpsJson.append(_lastWpJson);
				wpsJson.replace(start, end, _lastWpJson); 
				wpsJson.append(","); 
				 // QLog.getLogger().d(dTAG ,TAG+" setLastWp, added medias"+_lastWpJson );
				return true;
		}
		else 
			{
				Log.e(dTAG ,TAG+ " setLastWp, failed: new wp to set--->"+lastWp.toString());
			 if(null != _lastWp){
				 Log.e(dTAG ,TAG+ " track's _lastWp's time is: "+ _lastWp.getWb().getTime());
				 }
			return false;
			}
	}
	
	/*
	 * 新采集的wp加入到当前的轨迹中.
	 * 有一次装箱操作
	 */
	public boolean setLastWp(String jsonWp) {	
	//	Log.e(TAG +"set lastWp:" ,jsonWp);
		try{
			Waypoint wpobj = new Waypoint(jsonWp);	
			_lastWpJson=jsonWp;
			if( setLastWp( wpobj) ){ 		 
				if (TextUtils.isEmpty(_startWpJson ) || wpsJson ==null){
						_startWpJson = jsonWp;
						wpsJson = new StringBuffer();			
					}
				
				wpsJson.append(jsonWp); 
				wpsJson.append(",");
				//Log.e(TAG +"track wps json:",  wpsJson.toString());
				//Log.e(TAG +"set lastWp true:" ,jsonWp);
				return true;
			
		}else {
			// QLog.getLogger().d(dTAG,TAG +" set lastWp false:---->"+jsonWp);			
			}
		}catch(Exception e){
			 Log.e(dTAG ,TAG+ " setLastWp, failed: --->"+jsonWp );			
			 Utils.logStackTrace(e, dTAG);
		}
		return false;
	}
 
	/*
	 * load last/first wp from db.
	 */
	public  void  loadLastWp(String jsonWp) {	
	//	Log.e(TAG +"set lastWp:" ,jsonWp);
		try{
			Waypoint wpobj = new Waypoint(jsonWp);	
			_lastWpJson=jsonWp;
			if (TextUtils.isEmpty(_startWpJson ) ){
				_startWpJson = jsonWp;
			 	
			}
			if(tb.getStartWp() ==null ||_startWp == null){ 
				_startWp =_startWp==null?wpobj:_startWp;
				if(tb.getStartWp() ==null)tb.setStartWp(_startWp);
			 }
			
			_lastWp = wpobj;
			tb.setLastWp(_lastWp); 
		 
		}catch(Exception e){
			 Log.e(dTAG ,TAG+ " setLastWp, failed: --->"+jsonWp );			
			 Utils.logStackTrace(e, dTAG);
		}
		 
	}
 
	

	public Waypoint getStartWp() {
		return _startWp;
	}
	public void setStartWp(Waypoint wp) {
		_startWp =wp;
	}

	
	//TODO: check to use StringBuffer or just a String.
	public StringBuffer getJsonWps() {
		if (wpsJson ==null)  wpsJson = new StringBuffer();
		return wpsJson;
	}

	public String getLastJsonWp() {
		
		if(TextUtils.isEmpty(_lastWpJson)){
			if(  _lastWp !=null){
				_lastWpJson = _lastWp.toString();
			}
		}
		return _lastWpJson;
	}

	/*public void setLastWpJson(String lastWpJson) {
		setLastWp(lastWpJson);
		 
	}
*/
	public String getStartJsonWp() {
		if(TextUtils.isEmpty(_startWpJson )){			
			if( _startWp !=null){
			_startWpJson = _startWp.toString();
			// QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as _startWpJson = _startWp.toString()");
			}else if(getJsonWps().length()>0){
				_startWpJson =wpsJson.substring(0,wpsJson.indexOf("},", 0)+1 );	
				// QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as _startWpJson = wpsJson.substring");
			}else if (getTrackBean().getTrkseg().size()>0){
				Gson gson = new Gson();
				wpsJson.append(gson.toJson(getTrackBean().getTrkseg()));
				// QLog.getLogger().d(dTAG,TAG+" Start wp is null, set value as wpsJson = gson.toJson(getTrackBean().getTrkseg())");
				 getStartJsonWp();
			}else if(!TextUtils.isEmpty(_lastWpJson )){
				_startWpJson =_lastWpJson;
			}
				
		}
		return _startWpJson;
	}
 
 public void startNewTrack(TrackType trackType)
 {
	 tb = new Track_bean();
	 tb.setCreatTime(System.currentTimeMillis());
	 this.tb.setStatus(TrackStatus.RECORDING);
//	 this.tb.setStartTime(System.currentTimeMillis());
	 this.tb.setUserid(QiYouConstant.PV_USER_ID);
	 this.tb.setDistance(0);
	 this.tb.setGpsSpan(QiYouConstant.MAX_GPS_SPAN*QiYouConstant.WPS_SAVE_PERCENT_FACTOR);
	 tb.setType(trackType);
//	 this.tb.setComment("QiYouConstant.MAX_GPS_SPAN*QiYouConstant.WPS_SAVE_PERCENT_FACTORE: " +QiYouConstant.MAX_GPS_SPAN +","+ QiYouConstant.WPS_SAVE_PERCENT_FACTORE);
 }
	 
  

public void setLastRoadBear(Waypoint wp) {
//	QLog.getLogger().d(dTAG,TAG +" roadWps.size: "+roadWps.size());
	if(wp==null) return;
	
	
	if(tb.getRoadWps().size()==0){      //wp.getWb().getTurnFlag() ==0){// && !TextUtils.isEmpty(getStartJsonWp())){//first start wp
//		_lastRoadBear = wp; 
		_startWp.getWb().setTurnFlag(wpFlag.START);
		tb.getRoadWps().add(_startWp.getWb());
		_lastRbJson =getStartJsonWp();// _startWpJson;
		_rdWpsJson.append(_lastRbJson);
//		saveBear(wp.getWb());
 		return; 
	}

	wpFlag turnFlag =wp.getWb().getTurnFlag();
	
//	QLog.getLogger().dLog(dTAG,"wp.getWb().getTurnFlag() is:" +turnFlag);
	
	if(turnFlag==wpFlag.TURNLEFT || turnFlag ==wpFlag.TURNRIGHT || turnFlag ==wpFlag.TURNBACK){ //针对普通左右掉头路点
		if(wp.getWb().getBearDist()==0) return;
	}
	
 
	
	
//	saveBear(wp.getWb());
  
	
//	String  sb="\"  "+ (tb.getRoadWps().size()-1 ) +". "+getBearMsg(wp.getWb().getRoadBear());
//	String  sb="\"  "+ (tb.getRoadWps().size()-1 ) +". " + getBearMsg(wp.getWb().getBearing());

//	String turn= wp.getWb().getTurnFlag()>0?wp.getWb().getTurnFlag()==1?"左转":"反向":"右转";  
//	int turnFlag =tb.getRoadWps().get(tb.getRoadWps().size()).getTurnFlag();
	 

	
	String  sb="";
	if(turnFlag==wpFlag.TURNLEFT || turnFlag ==wpFlag.TURNRIGHT || turnFlag ==wpFlag.TURNBACK){ // turn bear wp
		
		if(wp.getWb().getBearDist()==0) return;
		
//		tb.getRoadWps().add(wp.getWb()); //add turn bear way point
//		Waypoint_bean lastBear=tb.getRoadWps().get(tb.getRoadWps().size()-2);
		Waypoint_bean lastBear=tb.getRoadWps().get(tb.getRoadWps().size()-1);
		if(lastBear==null) return;
		
		
		Location currentLocaiton = new Location("bear");
		currentLocaiton.setLatitude(wp.getWb().getLatitude());
		currentLocaiton.setLongitude(wp.getWb().getLongitude());
		
		Location lastLocation = new Location("bear");
		lastLocation.setLatitude(lastBear.getLatitude());
		lastLocation.setLongitude(lastBear.getLongitude());
		
		float bearDegree=lastLocation.bearingTo(currentLocaiton);
		
		String turn =turnFlag.toCHString();
		 
//		QLog.getLogger().dLog(dTAG,"wp.getWb().getTurnFlag().toCHString() is:" +turn);
				
		
		String format = "\"  沿%s方向， 前行%s后%s";//，至%s处\"";
				
 		     sb =String.format(format
//					  									,Utils.getBearMsg(lastBear.getBearing(),false)
					  									,Utils.getBearMsg(bearDegree,false)
					  									,Utils.getFormatedDistance( wp.getWb().getBearDist() )
					  									,turn
//					  									,Utils.getFormatedDistance( wp.getWb().getSumDist() ) 
					  			);
 			  
	/* if(wp.getWb().getBearDist()>1000)
 	 	_roadBook.append(sb+"\n"); */
			  
// 			QLog.getLogger().dLog(dTAG," roadbook is: " +sb);	  

// 			wp.getWb().setRoadBook(sb); 			
//    		tb.getRoadWps().get(tb.getRoadWps().size()-1).setRoadBook(sb);
    		lastBear.setRoadBook(sb);
    		lastBear.setBearDist( wp.getWb().getBearDist() );
 			tb.getRoadWps().add(wp.getWb()); //add turn bear way point
 			
 			
	//	tb.getRoadWps().add(_lastRoadBear.getWb());
//		QLog.getLogger().d(dTAG, TAG+" _lastRbJson" +_lastRbJson); 
		_lastRbJson =  this._lastWpJson.replace("\"roadBook\":\"\",", "");
		_lastRbJson = _lastRbJson.substring(0, _lastRbJson.length()-1) +   ",\"roadBook\":"+sb +"},";
//		QLog.getLogger().d(dTAG, TAG+" _lastRbJson" +_lastRbJson); 
//		QLog.getLogger().dLog(dTAG," _lastRbJson is: " +_lastRbJson);	
		_rdWpsJson.append(_lastRbJson);
		
		return;
		 
	}else  if(wp.getWb().getTurnFlag()==wpFlag.MAXR){ //maxR
		int i=0;
		for(Waypoint_bean wb:tb.getRoadWps()){
			if(wb==null)continue; 
			if(wb.getSumDist()<wp.getWb().getSumDist())
				i++;
			else if(i>1){
 
				wp.getWb().setRoadBook("到达本次记录最远位置  \n距起点直线距离  "
										+Utils.getFormatedDistance( getTrackBean().getMaxR())
										+"，运动距离 " + Utils.getFormatedDistance( wp.getWb().getSumDist()));	
				tb.getRoadWps().add(i, wp.getWb()); 
			     // QLog.getLogger().d(dTAG,TAG +" ......................到达本次记录最远位置" + Utils.getFormatedDistance( getTrackBean().getMaxR()));
//				_lastRbJson =wp.toString();
				break;
			}else{
				Log.e(dTAG,TAG+" Wrong wps....");
				i++;
			}
			
		}
	}  else if(turnFlag==wpFlag.END){ //last wp
		 sb="\"  到达本次记录的终点位置(结束)";
		 wp.getWb().setRoadBook(sb);
		 tb.getRoadWps().add(wp.getWb()); 
		_roadBook.append(sb);  
		
	}
	
 
}

/*
 *gpx from aiqilv lushu 
 */
public boolean isGpx(){
 	 return tb.getType()==TrackType.GPX;
}

public boolean isLushu(){
 	 return tb.getCreator()!=null &&tb.getCreator().startsWith("爱骑驴路书");
 }

private ArrayList<String> mdList;
/*
 * level : 0， standard GEO; 1: detail  ; 2: pic only
 */
public List<Map<String, String>>   getFootmark(int level,Boolean showMd) {
	
	 
	List<Map<String, String>> mData = new ArrayList<Map<String, String>>();
	QLog.getLogger().d(dTAG, TAG+String.format(" begin to get footmark...................."));
	mdList =new ArrayList<String>();
//	    String filePath =QiYouConstant.PHOTO_PATH +  tb.getTrackId()+"/" ; 
		int i=0;
//		long last=0;
		float last=0;
		float end=0;
		 if(getTrackBean().getType()!=TrackType.GPX)
		 if(level ==2 ||getTrackBean().getTrackId()<=0 && getTrackBean().getMdWps().size()>0) {
			 if(showMd)
				 mData.addAll(getMdlist(last,end));
//			 	 addNotes(mData,level);
			 return mData; 
		}
		
		 if(getTrackBean().getType()!=TrackType.GPX  && getTrackBean().getTrackId()<=0)return null;	    
		 
//		 boolean isGpx =tb.getCreator()!=null &&tb.getCreator().equalsIgnoreCase("爱骑驴路书");
//		 long lastSptime=0;
		 long lastTime=0;//=this.getStartWp().getWb().getTime();
		 long nextTime=0;
		 float lastSumdist=0;
		 Waypoint_bean nextWb = null;
//		 Waypoint_bean lastWb = null;
		 String last_currentGeo ="";
		 String last_nextGeo ="";
		 String current_district= "";
		 String last_district = "";
		 String current_street = "";
//		 String last_street = "";
		 String next_street = "";
		 boolean isSkiped =false;
		 boolean isTheLastOne=false;
		 int j=0;
		 long begintime=0;
		 
		 /*CopyOnWriteArrayList<Waypoint_bean>  wbs=Utils.getCleanWbs(tb.getRoadWps());*/
		 ArrayList<Waypoint_bean>  wbs=Utils.getCleanWbs(tb.getRoadWps());
//		 tb.getRoadWps().add(0,_startWp.getWb());
/*		 for(Waypoint_bean wb:tb.getRoadWps()){ 
			if(wb==null)continue;
			if(  wb.getTime()>lastTime){
//				 if(nextWb ==null && _startWp!=null  && wb.getTime()>_startWp.getWb().getTime()){
//					 nextWb =wb;
//				 }
				 wbs.add(wb);
				 lastTime =wb.getTime(); 
			} 
		 }*/
 		 
		 if(wbs.size()>0 && wbs.get(0).getTime()>_startWp.getWb().getTime())
			 wbs.add(0,_startWp.getWb());
		 if(wbs.size()>1 && wbs.get(wbs.size()-1).getTime()<_lastWp.getWb().getTime())
			 wbs.add(wbs.size()-1,_lastWp.getWb()); 
		 
		 tb.setRoadWps(wbs);
		 
		 lastTime =0;
		 String blank="       ";
		 String format =  blank+"[当前时间]：%s \n"
				   +blank+"[区间用时]：%s    [当前速度]：%.1f    [区间均速]：%.1f";
		 String	 sportData="";
		 String nextGeo ="";
		 String passedInfo="";
		 String title="";
		 String roadInfo = "";
		 String currentGeo ="";
		 Map<String, String> data  ;
		
		/*
		  data = new HashMap<String, String>();
		  data.put("time",_startWp.getWb().getTime()+","+_startWp.getWb().getTime());
		 if(_startWp!=null &&nextWb!=null  && (level ==0 || level==1 && _startWp.getWb().getGeo()!=null) ){   
			
//			  if(nextWb!=null){
			   sportData =nextWb.getSumDist()>0? String.format( format,
						Utils.getFormatedTime(_startWp.getWb().getTime()),
						Utils.getTimeCnt(nextWb.getTime()-_startWp.getWb().getTime(), true),
						_startWp.getWb().getSpeed(),
						3600*(nextWb.getSumDist())/(nextWb.getTime()-_startWp.getWb().getTime() ) 
					 ) :"";
		         roadInfo = "前行"+Utils.getFormatedDistance(nextWb.getDistance())  ;  
//			  }
		         
		         if(_startWp.getWb().getGeo()!=null  ) {		 
					 if ( nextWb.getGeo()!=null && !TextUtils.isEmpty(nextWb.getGeo().toString(","))){
							nextGeo =  nextWb.getGeo().toString(",");
					
				 
					  roadInfo =  nextWb.getRoadBook().replace("\"", "")  
					 			+ (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":("，将到达 " +nextGeo) );  
					}
					  currentGeo =_startWp.getWb().getGeo().toString(","); 
				 }
				 title=(TextUtils.isEmpty(currentGeo))?"": currentGeo ;
				 data.put("time",_startWp.getWb().getTime()+","+nextWb.getTime());
		 }
		 title=	title
				 + (TextUtils.isEmpty(sportData)?sportData:"\n"+sportData) 
				 +(TextUtils.isEmpty(roadInfo)?roadInfo:"\n"+roadInfo)  ;
		 data.put("title",  "起点" +blank +Utils.getFormatedTime(_startWp.getWb().getTime()) +"\n"+title);
//		 data.put("cmnt",_startWp.getWb().getComment());
		 data.put("cmnt", tb.getRoadWps().get(0).getComment());
		
		 mData.add(data); 	 */
		 
		 
		  if(end==0)last=-1; //to show pics taken before the first wp.
   	       if(showMd)			
	    	 mData.addAll(getMdlist(last,end));
		 
//   	    QLog.getLogger().d(dTAG, TAG+String.format("get footmark.tb.getRoadWps() size: "+tb.getRoadWps().size()));
		for(Waypoint_bean wb:tb.getRoadWps() ){   //TODO: Check why roadwps 没有包含first,lastwp
			j++;	 
			isTheLastOne =(j==(tb.getRoadWps().size()))&&(level ==1)&& wb.getDistance()>0;
//			if(wb!=null && !TextUtils.isEmpty(wb.getRoadBook())
//					&& wb.getTime()>0 &&wb.getSpeed()>0 && wb.getDistance()>0 &&
//					(lastTime==0 ||wb.getTime()>lastTime) || isTheLastOne){  
				if( i<tb.getRoadWps().size()|| isTheLastOne){  
//					QLog.getLogger().d(dTAG, TAG+String.format("get footmark...................."));  
//					QLog.getLogger().d(dTAG, TAG+String.format("get footmark.i is: "+i));
//					QLog.getLogger().d(dTAG, TAG+String.format("get footmark.isTheLastOne is: "+isTheLastOne));
				 nextWb=null;    
				 currentGeo ="";
				
				if(lastTime==0)lastTime= getStartWp().getWb().getTime(); 
// 				if(wb.getTime()<lastTime)continue;   
 				i++;
 				if(wb.getTurnFlag()==wpFlag.MAXR){
					 data = new HashMap<String, String>();
					 data.put("time",wb.getTime()+","+wb.getTime());
					 title=blank+"[当前时间]：" +Utils.getFormatedTime(wb.getTime()) +   String.format("\n%s[当前速度]：%.1f" ,blank,wb.getSpeed())+"\n"+wb.getRoadBook();
					 data.put("title",title );
					 data.put("cmnt",wb.getComment());
					 mData.add(data); 
					 continue;
				}
 			
 				
 				
 				
				if (wb.getGeo()!=null && !TextUtils.isEmpty(wb.getGeo().toString(","))){
					currentGeo =  wb.getGeo().toString(",");
					current_district =wb.getGeo().getDistrict();
					current_street =wb.getGeo().getStreet();
				}
					
//				TextUtils.isEmpty(currentGeo) currentGeo lastGEO
				
//				int k=1;
//				while ((nextWb==null || nextWb.getTime()<lastTime || nextWb.getGeo() ==null ||TextUtils.isEmpty(nextWb.getGeo().toString(",")))  && i+k<(tb.getRoadWps().size()-1)){					
//					nextWb=tb.getRoadWps().get(i+k++); 
//				} 
//				k=1;
				if(j<(tb.getRoadWps().size()))
					nextWb=tb.getRoadWps().get(j); 
				
//				if(nextWb!=null && nextWb.getTime()<wb.getTime())continue;
				if(nextWb!=null && nextWb.getTurnFlag()==wpFlag.MAXR &&j<(tb.getRoadWps().size())){ 
					 continue;
				}
				
			    nextGeo ="";
				next_street ="";
				if (nextWb!=null  && nextWb.getGeo()!=null && !TextUtils.isEmpty(nextWb.getGeo().toString(","))){
					nextGeo =  nextWb.getGeo().toString(",");
					next_street = nextWb.getGeo().getStreet();
					
				 }
				if(nextWb!=null)
					nextTime =nextWb.getTime();
				
				//build the wp title
				 data = new HashMap<String, String>();
//				 String sportData ="";
//				 if(wb.getTime()>0 &&wb.getSpeed()>0)
				
			/*	 String	 sportData= wb.getTime()-lastTime==0?"":String.format(  //blank+"总距离"+
						 							blank+"[当前时间]：%s \n"
						 						   +blank+"[区间用时]：%s    [当前速度]：%.1f    [区间均速]：%.1f",
						 Utils.getFormatedTime(wb.getTime()),
						 Utils.getTimeCnt(wb.getTime()-lastTime, true),
						 wb.getSpeed(),
						 3600*(wb.getSumDist()-lastSumdist)/(wb.getTime()-lastTime)*/
				
			/*	 
				    	 sportData= (nextWb==null && _lastWp.getWb().getTime()>wb.getTime())?
								 String.format( format,
											Utils.getFormatedTime(wb.getTime()),
											Utils.getTimeCnt(_lastWp.getWb().getTime() -wb.getTime(), true),
											wb.getSpeed(),
											3600*(_lastWp.getWb().getSumDist()-wb.getSumDist())/(_lastWp.getWb().getTime() -wb.getTime()) 
										 )
								 : 
									String.format( format,
									Utils.getFormatedTime(wb.getTime()),
									Utils.getTimeCnt(nextTime -wb.getTime(), true),
									wb.getSpeed(),
									3600*(nextWb.getSumDist()-wb.getSumDist())/(nextTime -wb.getTime()) 
								 );*/
						if(tb.getType()!=TrackType.GPX && wb.getTime()>0)								 
						 sportData= (nextWb==null && _lastWp.getWb().getTime()>wb.getTime())?
								 String.format( format,
											Utils.getFormatedTime(wb.getTime()),
											Utils.getTimeCnt(_lastWp.getWb().getTime() -wb.getTime(), true),
											wb.getSpeed(),
											3600*(_lastWp.getWb().getSumDist()-wb.getSumDist())/(_lastWp.getWb().getTime() -wb.getTime()) 
										 )
								 :( nextWb==null?"":
									String.format( format,
										Utils.getFormatedTime(wb.getTime()),
										Utils.getTimeCnt(nextTime -wb.getTime(), true),
										wb.getSpeed(),
										3600*(nextWb.getSumDist()-wb.getSumDist())/(nextTime -wb.getTime())
									)
								 );
						 
								 
				   title="";
				   roadInfo =wb.getDistance()>0?
					   "前行"+Utils.getFormatedDistance(wb.getDistance()) + ",前方到达"+Utils.getFormatedDistance(wb.getSumDist())+"处"
					   :"";
//				 if(level ==0 || level ==1 &&  !TextUtils.isEmpty(nextGeo)){ 
				 
				 if(level ==0  ){ 
					
					 begintime =  wb.getTime() ;
					/* title=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ; 
					 title=	title+ sportData  ;*/
					 
//					 QLog.getLogger().d(dTAG, TAG +"  currentGeo is :" + currentGeo);
//					 QLog.getLogger().d(dTAG, TAG +"  title is :" + title);
					 
					/* if(nextWb!=null && nextWb.getTime()>wb.getTime()) 
//						 roadInfo =  isGpx()? TextUtils.isEmpty(nextWb.getRoadBook())?nextWb.getComment().replace("\"", ""):nextWb.getRoadBook().replace("\"", "")
//								 			  :wb.getRoadBook().replace("\"", "")
						 roadInfo = tb.getType()==TrackType.GPX && TextUtils.isEmpty(wb.getRoadBook())? wb.getComment().replace("\"", "") 
								 : nextWb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") 
						 			+ (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":("，将到达 " +nextGeo) );*/
						 
						 if( tb.getType()==TrackType.GPX ){
							/* roadInfo = wb.getRoadBook().replace("\"", "")+( TextUtils.isEmpty(wb.getComment())?"":wb.getComment().replace("\"", ""));*/
							 roadInfo =( TextUtils.isEmpty(wb.getComment())?"":wb.getComment().replace("\"", "")+"\n")+ wb.getRoadBook().replace("\"", "");
						 }else/* if(nextWb!=null)*/{
							 roadInfo =  wb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") 
							 			+ (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":("，将到达 " +nextGeo) );
						 }
							 
						 
//						 roadInfo = isGpx() && TextUtils.isEmpty(nextWb.getRoadBook())? nextWb.getComment().replace("\"", "") 
//								 	: nextWb.getRoadBook().replace("\"", "")// wb.getRoadBook().replace("\"", "") 
//						 				+ (TextUtils.isEmpty(nextGeo)||nextGeo.equalsIgnoreCase(last_nextGeo)?"":("，将到达 " +nextGeo) );
					 
//					 title =title + (TextUtils.isEmpty(roadInfo)?"":"\n"+ roadInfo)  ;
					  
					 
//				 } else if( level ==1 &&  (!TextUtils.isEmpty(currentGeo)||isTheLastOne)){
//				 } else if( level ==1 && (!TextUtils.isEmpty(currentGeo) ||nextWb==null)){
				 } else if( level ==1 &&  !TextUtils.isEmpty(currentGeo)||isSkiped  ||i==1){
//				 } else if( level ==1 &&  currentGeo!=null ){
//				 } else if( level ==1  ||isTheLastOne ){ 
					 
					 
					
					 if((  current_district==null ||last_district==null ||current_district.equalsIgnoreCase(last_district)) 
//							  && (current_street.equalsIgnoreCase(next_street)|| TextUtils.isEmpty(next_street)) 
// 							  || (currentGeo.equalsIgnoreCase(nextGeo) || currentGeo.equalsIgnoreCase(last_currentGeo) && nextGeo.equalsIgnoreCase(last_nextGeo))  
							 
 							 && (current_street==next_street|| TextUtils.isEmpty(next_street)) 
							  || (currentGeo==nextGeo || (currentGeo==last_currentGeo) && (nextGeo==last_nextGeo))
							 
							 ){
							 isSkiped =true;
//						 isTheLastOne =isTheLastOne&&(wb.getTime()>lastTime);
						 if(!isTheLastOne )
						 {
							 begintime = begintime==0?wb.getTime():begintime;
							 continue;						 
						 }
					 }
//					 String title=(currentGeo.equalsIgnoreCase(last_currentGeo)?"":currentGeo) 
//							 + sportData + "\n"  +wb.getRoadBook().replace("\"", "")
//							 + (nextGeo.equalsIgnoreCase(last_nextGeo)?"":nextGeo );
					 
//					 String roadInfo = isSkiped?("延  " +wb.getGeo().toString(",") +" 前行" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist)):wb.getRoadBook().replace("\"", "");
//					 String title= currentGeo 
//							 + sportData + "\n"  
//							 + roadInfo
//							 +  nextGeo ;
					 
//					 String roadInfo =  "延 " +wb.getGeo().toString(",") +"前行" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist) ;  
//					 String roadInfo = "";
					 passedInfo="";
					 if(nextWb!=null && nextWb.getTime()>wb.getTime()) {
						 	 passedInfo=isSkiped?"[延" + current_street +"累计运动" + Utils.getFormatedDistance(wb.getSumDist()-lastSumdist) +"后]\n" :"";
	 
						     roadInfo=   (isTheLastOne ? "" : nextWb.getRoadBook().replace("\"", "") )
								 +  (TextUtils.isEmpty(next_street)?"":("，将到达 " +next_street));
					 }
					/* title=  passedInfo ;
					 title +=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ;
					 title +=  sportData ;*/
//							 + (TextUtils.isEmpty(roadInfo)?"\n将到达终点附近.":"\n"+ roadInfo)  ;
						 	 
						
					
					 isSkiped=false;
				 } else{
					 continue;
				 }
//				 QLog.getLogger().d(dTAG, TAG +"  title is :" + title);
				 
				 
				 
				 
				 
				 
//				 if(i==1)
				 if(i<2 && wb.getTime()<=_startWp.getWb().getTime()){	  
						title  ="起点" +blank +(isGpx()?"":Utils.getFormatedTime(_startWp.getWb().getTime())) +(isGpx()?"\n\n":"\n"); 
				 }
				 title +=  passedInfo ;
				 title +=(TextUtils.isEmpty(currentGeo)||currentGeo.equalsIgnoreCase(last_currentGeo))?"": currentGeo+"\n" ;
				 title +=  sportData ; 
				 
				 if(wb.getTurnFlag()==wpFlag.END ||nextWb==null) 
					 roadInfo=  ( _lastWp.getWb().getSumDist()>last? 
						    ("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +","
		 					+" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n") 
		 					:""
	 				    )	
	 					+"\n"+"终点   "+ (_lastWp.getWb().getGeo()!=null?_lastWp.getWb().getGeo().toString(","):"")
	 					
	 					+(isGpx()?"":"\n" +Utils.getFormatedTime(_lastWp.getWb().getTime()))
//	 					+Utils.getFormatedTime(tb.getEndTime())
//	 					+Utils.getFormatedTime(_lastWp.getWb().getTime()) 
	 			 	  	; 
				  
				 
				 title += TextUtils.isEmpty(roadInfo)?"":"\n"+ roadInfo   ;
				
				 
				 
				 
				 
				 
				 
				 if(!TextUtils.isEmpty(title)){
					 
//					 QLog.getLogger().d(dTAG, TAG +"  title is :" + 1+title+1);
					 begintime =begintime>0?begintime:wb.getTime();
					 
					 data.put("title",title) ; 
	//				 data.put("uri",null);
					 /*data.put("cmnt",(nextWb!=null?nextWb.getComment():wb.getComment() ));*/
					 data.put("cmnt",(wb.getComment() ));
	//				 data.put("time",lastTime+","+String.valueOf(wb.getTime()));
					 data.put("time",begintime+","+ (nextWb!=null?nextTime:_lastWp.getWb().getTime() ));
					 mData.add(data);  
				 }
				 
				 //build the wp pics if there is any.
				 if(nextWb!=null ){
//				     end =wb.getSumDist();  
//				     if(end==0)last=-1; //to avoid showing all the pics for the first wp.
//						QLog.getLogger().d(dTAG, TAG+String.format(" get mdlist start is %s, end is %s",last,end));
//						
//				     if(showMd)			
//				    	 mData.addAll(getMdlist(last,end));
				     
				     
				     last =wb.getSumDist();  
				     end =nextWb.getSumDist();
				     if(end==0)last=-1; //to avoid showing all the pics for the first wp.
//						QLog.getLogger().d(dTAG, TAG+String.format(" get mdlist start is %s, end is %s",last,end));
						
				     if(showMd)			
				    	 mData.addAll(getMdlist(last,end));
				 }
			 begintime =0;    
//			 lastWb=wb;
			 last =wb.getSumDist(); 
		     lastTime=wb.getTime();
		     lastSumdist=wb.getSumDist();
//		     lastSptime =wb.getSportTime();
		     
		     last_currentGeo =currentGeo;
			 last_nextGeo =nextGeo;
			 last_district=current_district;
//			 last_street=current_street;
			}
		}
		
	
		if(i==0 && showMd){
			
			mData.addAll(getMdlist(last,end));
		}
		
		
	/*	if(  _lastWp.getWb().getGeo()!=null || tb.getStatus()==QiYouConstant.TRACK_STATUS_FINISHED){
			 lastTime=nextTime>lastTime?nextTime:lastTime;
			 nextTime= _lastWp.getWb().getTime();
			 sportData= (nextTime>lastTime)?
					    String.format( format,
								Utils.getFormatedTime(lastTime),
								Utils.getTimeCnt(nextTime-lastTime, true),
								_lastWp.getWb().getSpeed(),
								3600*(_lastWp.getWb().getSumDist()-last)/(nextTime-lastTime ) 
							 ):"";
			 
//			 roadInfo= String.format("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +","
//					 					+" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n" 
//					 					+"终点 "+ _lastWp.getWb().getGeo().toString(",") )
//					 					+Utils.getFormatedTime(tb.getEndTime())
//					 					; 
			 roadInfo=  ( _lastWp.getWb().getSumDist()>last? 
						    ("前行"+Utils.getFormatedDistance(_lastWp.getWb().getSumDist()-last) +","
		 					+" 到达"+Utils.getFormatedDistance(tb.getDistance())+"处\n") 
		 					:""
	 				    )	
	 					+"\n"+"终点   "+ (_lastWp.getWb().getGeo()!=null?_lastWp.getWb().getGeo().toString(","):"")
	 					+"\n" +Utils.getFormatedTime(_lastWp.getWb().getTime())
//	 					+Utils.getFormatedTime(tb.getEndTime())
//	 					+Utils.getFormatedTime(_lastWp.getWb().getTime()) 
	 			 	  	; 
			 
			 title=  (!TextUtils.isEmpty(nextGeo)? nextGeo+"\n":nextGeo) +
					 (!TextUtils.isEmpty(sportData)?sportData+ "\n":"") + 
					 roadInfo; 
					 
			 
			 data = new HashMap<String, String>();
			 data.put("title", title);
			 data.put("time",lastTime+","+nextTime);
			 data.put("cmnt",_lastWp.getWb().getComment());
			 mData.add(data); 
		 }*/
		
//		 data = new HashMap<String, String>();
//		 data.put("title", String.format("终点位置 " +(_lastWp!=null && _lastWp.getWb().getGeo()!=null?   _lastWp.getWb().getGeo().toString(",") :"" )));
//		 data.put("time",_lastWp.getWb().getTime()+","+_lastWp.getWb().getTime()); 
//		 mData.add(data); 
		if(_lastWp!=null) 
 		 end=_lastWp.getWb().getSumDist();   //show pics that before the last new waypoint created.
	     if(end==0)last=-1;  
	     if(showMd)			
	    	 mData.addAll(getMdlist(last,end)); 
//		GenFootmark(true,_roadBook.toString());  //when new geo populated, the footmark file content will be cleared.force to fill the the content.
	 
//		addNotes(mData,level);
     /* for(Waypoint_bean wb1:tb.getRoadWps()){
			 
			 QLog.getLogger().d(dTAG,  "30 cust wp  turn flag" + wb1.getTurnFlag().toCHString());
		} */
	      
	return mData;
}
 

public List<Map<String, String>>   getMdlist(float start,float end){
	List<Map<String, String>> mData = new ArrayList<Map<String, String>>();
	Map<String, String> data ;
//	String filePath ; 
	 for(Waypoint_bean mwb:tb.getMdWps()){  
		  
//					if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){
			if(mwb!=null && (mwb.getSumDist()>=start && mwb.getSumDist()<=end || start==end && start==0)){
				  GEOaddress geo =getGeo(mwb.getTime());
				  String title=geo==null?"":geo.toString(",");
				for(Media md: mwb.getMedias()){
					if(md.getStatus()==mediaStatus.DELETED||md.getStatus()==mediaStatus.HIDED)
						continue;
				 
//					QLog.getLogger().d(dTAG, TAG+String.format("PICS met condition, start is %s, end is %s",start,end));

//					filePath =this.getMediaPah(md.getType());
				    data = new HashMap<String, String>();
				    title +="    "+Utils.getFormatedTime(md.getTime());
				    data.put("title",title);
					
//				    String  path = QiYouConstant.BASE_MD_URL+md.getSvrUri();//getValidMdUrl(md);//md.getUri();	
				    
				    String  path =  getValidMdUrl(md,true);
				    
				     

// 					QLog.getLogger().d(dTAG, TAG+ " footmark web pic url is  " +path);

				    
				    if(mdList.contains(path))continue;
				    mdList.add(path);
//					path =path.contains(QiYouConstant.PHOTO_PATH)?path:filePath +path; //to remove.
//					path = filePath +path; //to remove.
					data.put("uri",path);
					data.put("mdType",md.getType().toString());
					
					if(!TextUtils.isEmpty( md.getComment()))										 
						data.put("cmnt",md.getComment());	 
					data.put("time",String.valueOf(md.getTime()));
					mData.add(data);
					
					/*switch( md.getType() ){
						case  PIC:
							break;	 
						case MAP:
							break;
						case SOUND:
							break;
						case VIDEO:
							break;
						default:
							break;
						 
					}*/
				}
			}
			
		 } 
/*	 
	   data = new HashMap<String, String>();
			 data.put("title","") ; 
	 		 data.put("cmnt","");
	 		 data.put("time","");
	 		 data.put("uri","");
			 data.put("mdType",mediaType.PIC.toString());
			 mData.add(data); */
			 
	return mData;
	
}

GEOaddress getGeo(long time){
	 for(Waypoint_bean wb:tb.getRoadWps()){ 
			if(wb==null)continue;
			if(  wb.getTime()==time){
				return wb.getGeo();
			}
	 }
	 return null;
}


 public String getValidMdUrl(Media md,boolean isThumb){
	if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){
		File f = new File(md.getUri());
		 // QLog.getLogger().d(dTAG,TAG+" getting valid md url: "+ md.getUri()); 
		if(f.exists()){
			 return md.getUri();
		 
		}else{
//			if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){
			if(tb.getSvrNumber()>0 ){
//				return QiYouConstant.BASE_MD_URL+md.getSvrUri() ;
				return QiYouConstant.BASE_MD_URL+(isThumb?md.getSvrThumbUrl():md.getSvrUri()) ;
			 
			}
		}
	}
	return "";
}
  /*void addNotes(List<Map<String, String>> mData,int level){
	String notice="";
	if(mData.size()==0 ){
		notice="还没有发现小脚印...";
		if(level ==1){
			notice ="没找到详细地址数据...连接wifi后会自动生成详细地址数据...";
		}else if(level==2){
			notice ="没找到照片...快去拍些亮丽的片片吧" ;
		}
	}else{
		notice ="提示: 长按足迹条目可在地图定位";
//		if(level ==1){
//			notice ="提示: 长按可地图定位";
//		}else 
			if(level==2){
			notice ="提示: 点击图片可进入浏览模式,长按图片可地图定位" ;
		}
	}
	
		HashMap<String, String>  data = new HashMap<String, String>();
		 data.put("title",notice ) ;
		 data.put("picUrl",null);
		 data.put("picCmnt",null);
		 mData.add(0,data);  
}*/



//public String[] getPicList(){
// return getPicList(0,false,true);
//}
public String[] getPicList(int cnt){
	 return getPicList(cnt,true,true);
	}
public String[] getValidPicList(boolean isThumbs){
	 return getPicList(0,true,isThumbs);
	}


public String[] getPicList(int cnt,boolean validOnly,boolean isThumbs){
	
    ArrayList<String> al = new ArrayList<String>();
	int i=0;
	String protocol ="file://";
	String webUrl =QiYouConstant.BASE_MD_URL;
	File f ;
	 for(Waypoint_bean mwb:tb.getMdWps()){
		 if(mwb!=null ){
			 if(cnt>0 && i>=cnt)break;
			 
				for(Media md: mwb.getMedias()){
					if(cnt==0|| cnt>0 && i<=cnt){
						
						if(validOnly ){
							if( md.getStatus()==mediaStatus.DELETED || md.getStatus()==mediaStatus.HIDED){
								continue;
							} 
						}
						
						if(tb.getSvrNumber()>0 ){
							f = new File(md.getUri());
							if(f.exists()){
								al.add(protocol+md.getUri());
								 i++;
							}else{
								al.add(webUrl+(isThumbs?md.getSvrThumbUrl():md.getSvrUri()));
								i++;
							}
						}else{
							al.add(protocol+md.getUri());
							i++;
						}
						
						
				/*		if(validOnly){
							if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){
								f = new File(md.getUri());
								if(f.exists()){
									al.add(protocol+md.getUri());
									 i++;
								}else{
//									if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){
									if(tb.getSvrNumber()>0 ){
										al.add(webUrl+md.getSvrUri());
										i++;
									}
								}
							}
						}else{
							if(tb.getSvrNumber()>0 && tb.getUserid()!=QiYouConstant.PV_USER_ID){
								al.add(webUrl+md.getUri());
								i++;
							}else{
								i++;
								al.add(protocol+md.getUri());
							}
						}*/
						
					}
//				    QLog.getLogger().d(dTAG,TAG+"  protocol+md.getUri()   "+  protocol + md.getUri());
		
					/*switch( md.getType()){
					case PIC:  
						break;					 
					case MAP:
						break;
					case SOUND:
						break;
					case VIDEO:
						break;
					default:
						break;
				}*/
		 }
	  }
	 }
	 String[] picUrls = new String[al.size()];
	 al.toArray(picUrls);
	 return picUrls;
}

public String[] getWebPicList(int cnt,boolean validOnly){
	
    ArrayList<String> al = new ArrayList<String>();
	int i=0; 
	String webUrl =QiYouConstant.BASE_MD_URL;
//	File f ;
	 for(Waypoint_bean mwb:tb.getMdWps()){
		 if(mwb!=null ){
			 if(cnt>0 && i>=cnt)break; 
				for(Media md: mwb.getMedias()){
				  if(!TextUtils.isEmpty(md.getSvrUri()))
					if(cnt==0|| cnt>0 && i<=cnt){
						if(validOnly){
							if(md.getStatus()!=mediaStatus.DELETED && md.getStatus()!=mediaStatus.HIDED){ 
										al.add(webUrl+md.getSvrThumbUrl());
										i++; 
										// QLog.getLogger().d(dTAG,TAG+"  get web md url is:"+  webUrl+md.getSvrThumbUrl());
							}
						}else{ 
								al.add(webUrl+md.getSvrUri());
								i++; 
								// QLog.getLogger().d(dTAG,TAG+"  get web md url is:"+  webUrl+md.getSvrThumbUrl());
						}
					}
 		 
		 }
	  }
	 }
	 String[] picUrls = new String[al.size()];
	 al.toArray(picUrls);
	 return picUrls;
}

public String getMediaPah(mediaType mdType){
	String picPath=QiYouConstant.MEDIA_PATH +mdType +"/";
	picPath+=mdType==mediaType.MAP?"i7lv":
					 	getTrackBean().getTrackId()>0? 
					 			QiYouConstant.MEDIA_FOLDER_PREFIX+getTrackBean().getTrackId()
					 			:"i7lv";
	
	return picPath+"/";
}

public boolean isContentExist(){
	if(getTrackBean().getTrackId()<=0)
		return false;
	  File file = new File(getContentPah()); 
	  return file.exists(); 
	
}

public boolean readContent(){
	if(getTrackBean().getTrackId()<=0)
		return false;
	else{
		wpsJson=new StringBuffer();
		try { 
			
			wpsJson.append(Utils.readSDFile(getContentPah()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
		}
	}
	return true;
}


public String getContentPah(){
//	return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+".txt";
	return Utils.getContentPah(getTrackBean().getTrackId());
}
public boolean saveContent(){
	return saveContent(true);
}

public boolean saveContent(boolean isAppend){
	if(getTrackBean().getTrackId()<=0)
		return false;
	else{
		try {
		 
			if(TextUtils.isEmpty(getJsonWps().toString()))
				getJsonWps().append(wps2json(getTrackBean().getTrkseg())); 
			
			// QLog.getLogger().dLog(dTAG, "saved trackseg content is: "+getJsonWps().toString());
			Utils.writeSDFile(getContentPah(), getJsonWps().toString(), isAppend);
//			Utils.writeSDFile(getContentPah(), wpsJson.toString(), isAppend);getJsonWps()
			wpsJson=new StringBuffer();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
		}
	}
	return true;
}
public String getBearContentPah(){
//	return QiYouConstant.CONTENT_SD_DIR + getTrackBean().getTrackId()+"b.txt";
	return Utils.getBearContentPah(getTrackBean().getTrackId());
}
public boolean saveBearContent(){
	return saveBearContent(true);
}
public boolean saveBearContent(boolean isAppend){
	if(getTrackBean().getTrackId()<=0)
		return false;
	else{
		try {
		 
			if(TextUtils.isEmpty(this.getRdWpsJson() )){
				getRdWpsJson().append(wps2json(getTrackBean().getRoadWps()));
				// QLog.getLogger().dLog(dTAG, "saved RoadWps content is: "+getRdWpsJson().toString());
				Utils.writeSDFile(getBearContentPah(), getRdWpsJson().toString(), false);
				return true;
			}
			if(!TextUtils.isEmpty(_rdWpsJson )){
				Utils.writeSDFile(getBearContentPah(), getRdWpsJson().toString(), isAppend);				
				_rdWpsJson=new StringBuffer();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
		}
	}
	return true;
}

public boolean isBearContentExist(){
	if(getTrackBean().getTrackId()<=0)
		return false;
	  File file = new File(getBearContentPah()); 
	  return file.exists(); 
	
}

public boolean readBearContent(){
	if(getTrackBean().getTrackId()<=0)
		return false;
	else{
		_rdWpsJson=new StringBuffer();
		try { 
			
			_rdWpsJson.append(Utils.readSDFile(getBearContentPah()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
		}
	}
	return true;
}


public static boolean saveBear(Waypoint_bean wb){
	if(wb.getLatitude()==0||wb.getLongitude()==0)return false; 
	 
		try { 
//			Utils.writeSDFile(QiYouConstant.BEAR_TEXT,((int)(Utils.getbdLat(wb.getLatitude(),wb.getLongitude()))*1E6 ) +
//					","+(int)(Utils.getbdLon(wb.getLatitude(),wb.getLongitude()))*1E6+";", true);
//			String strlatlon= wb.getLatitude() + ","+wb.getLongitude();
//			String bearString=""; 
//			 bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT);
//			 if(TextUtils.isEmpty(bearString)||!bearString.contains(strlatlon))		     
			
			//TODO: to record each track in itsown bear text.
				 Utils.writeSDFile(QiYouConstant.BEAR_TEXT,wb.getLatitude() + ","+wb.getLongitude()+";", true);
			 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
			return false;
		 
		}
	 
	return true;
}



public void assemblyContent(){
	if(readContent()){
		String json=wpsJson.toString();
		if(!TextUtils.isEmpty(json)){	
	//		json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");		
			json=getCleanJson(json); 
	//			tb.setTrksegs(wps);	
			if(!json.startsWith("["))
				json ="["+json ; 
			if(!json.endsWith("]")){
				json =json+"]";
			}
			try {
				getTrackBean().setTrksegs(getWPS( new Gson(),json));
			} catch (Exception e) {				
				Utils.logStackTrace(e, dTAG);
				if(!TextUtils.isEmpty(json)){
					Log.e(dTAG ,TAG+" below is wps jsonWps---------------");
					Log.e(dTAG ,TAG+ json );
				}
			}
		}
		wpsJson=new StringBuffer();  //TODO check if it will cause :     //put it before convert to wps, in case failed, then recovery track will miss existed wps in db.
	}
	
}



private void assemblyBearContent(){
	if(readBearContent()){
		String json=_rdWpsJson.toString();
		if(!TextUtils.isEmpty(json)){	
	//		json= jsonWps.replace("[","").replace("]", "").replace(" ","").replace("}{", "},{").replace("null", "");		
			json=getCleanJson(json); 
	//			tb.setTrksegs(wps);	
			if(!json.startsWith("["))
				json ="["+json ; 
			if(!json.endsWith("]")){
				json =json+"]";
			}
			try { 
				getTrackBean().setRoadWps(getWPS( new Gson(),json));
				// QLog.getLogger().d(dTAG, TAG +" "+" Loading bear content from bear text "+ getBearContentPah() +"........................................");
			} catch (Exception e) {				
				Utils.logStackTrace(e, dTAG);
				if(!TextUtils.isEmpty(json)){
					Log.e(dTAG ,TAG+" below is wps bearRoadWps---------------");
					Log.e(dTAG ,TAG+ json );
				}
			}
		}
		_rdWpsJson=new StringBuffer();  //TODO check if it will cause :     //put it before convert to wps, in case failed, then recovery track will miss existed wps in db.
	}
	
}



public String getStaticMapPath(){
	return getMediaPah(mediaType.MAP);
}

public String getStaticMap(){
	
	String staticMapPath ="file://"+getStaticMapPath() + getStaticMapUrl().hashCode()+".png" ; 
	File staticMap = new File(staticMapPath);
	try {
	   if(!staticMap.exists()){  //to get it from http://api.map.baidu.com/staticimage 
		   staticMapPath = getStaticMapUrl();
	   } 
  	} catch (Exception e1) {
		// TODO Auto-generated catch block
		Utils.logStackTrace(e1, TAG);
	}
	 
	  return staticMapPath ;
}
public String getStaticMapUrl(){
	
//	  String webStaticUrl=Utils.getBaiduStaticMapUrl(this);
	 
/*	if(this.getTrackBean().getRoadWps().size()<2)      
		return getStaticMapPath()+getTrackBean().getTrackId()+".png" ;
	else
		return Utils.getBaiduStaticMapUrl(this);
	*/
	String staticDir=getStaticMapPath();
	File dir = new File(staticDir);	
	if(!dir.exists()) dir.mkdirs();// 创建文件夹	
	
	String static_url_file=staticDir + String.valueOf(this.getTrackBean().getEndTime());
	String static_url=""; 
	 
	File staticMap = new File(static_url_file);
		try {
		   if(!staticMap.exists()){  //to get it from http://api.map.baidu.com/staticimage 
			   if(getTrackBean().getTrackId()>0 && getTrackBean().getTrkseg().size()==0){
				   assemblyContent();
			   }
			   static_url = Utils.getBaiduStaticMapUrl(this); 
			   staticMap.createNewFile();
			   Utils.writeSDFile(static_url_file,static_url,false);
		   }else
		   {
			   static_url =  Utils.readSDFile(static_url_file);
		   }
	  	} catch (Exception e1) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e1, TAG);
		}
		
	 return static_url;
	
}


public boolean isStaticMapExist(){
	
 File myFile = new File(getStaticMap());
 return myFile.exists();
	 
}


/*public StringBuffer getRoadBook(Boolean showMd) { 
	
	if(_roadBook.length()==0 && tb.getRoadWps()!=null)
	{		
		_roadBook = new StringBuffer();
		String fm = getFootmark();
		if(!TextUtils.isEmpty(fm)){
			_roadBook.append( getFootmark());			
			return _roadBook;
		}
		 
//		_roadBook.append("<html><body>");
		_roadBook.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
		 _roadBook.append(String.format(QiYouConstant.FOOT_MARK_TITLE_TEMPLATE,"我的足迹")); 
		 
		 if(_startWp.getWb().getGeo()!=null  ) 
			 _roadBook.append(String.format("起点:" + QiYouConstant.FOOT_MARK_TURN_TEMPLATE,_startWp.getWb().getGeo().toString(","))+"\n");
		 
		int i=0;
//		long last=0;
		float last=0;
		for(Waypoint_bean wb:tb.getRoadWps() ){
			if(wb!=null && !TextUtils.isEmpty(wb.getRoadBook())){ 
				 
			 _roadBook.append(++i+ ")  "
					 +String.format(QiYouConstant.FOOT_MARK_TURN_TEMPLATE,wb.getRoadBook())//.replace("\"", ""))
					 +"\n"); 
			 
//			 if(showMd)_roadBook.append(getMds(last,wb.getTime()));
			 if(showMd)_roadBook.append(getMds(last,wb.getSumDist()));
			 
			 
//			 last =i==0?0:wb.getTime();
			 last =i==0?0:wb.getSumDist();
			 
			}
		}
		
		 if(  _lastWp.getWb().getGeo()!=null )
			 _roadBook.append(String.format("终点:" + QiYouConstant.FOOT_MARK_TURN_TEMPLATE,_lastWp.getWb().getGeo().toString(","))+"\n");
		 
		GenFootmark(true,_roadBook.toString());  //when new geo populated, the footmark file content will be cleared.force to fill the the content.
		
		
//		for(int i=0;i<tb.getRoadWps().size();i++){
//			if(tb.getRoadWps().get(i)!=null && tb.getRoadWps().get(i).getRoadBook()!=null){
//			 _roadBook.append(tb.getRoadWps().get(i).getRoadBook().replace("\"", "")+"\n");
//			}
//		}
//		_roadBook.append("</body></html>");
	}
	
	
	return _roadBook;
}
*/


//String getMds(long start,long end){
/*String getMds(float start,float end){
	

	String rt="";
 	String filePath;// =QiYouConstant.PHOTO_PATH +  tb.getTrackId()+"/" ;
	for(Waypoint_bean wb:tb.getMdWps()){
//		if(wb!=null && wb.getTime()>=start && wb.getTime()<=end){
		if(wb!=null && wb.getSumDist()>=start && wb.getSumDist()<=end){
			for(Media md: wb.getMedias()){
				filePath =this.getMediaPah(md.getType());
				String  path = md.getUri();
				path = filePath +path; //to remove. 
				rt += "<p>"
					 + "<img src=\""  
					+ path  
					 + "\"/>" 
					+ "</p>";
				if(!TextUtils.isEmpty( md.getComment()))
					rt +=   "图片说明: " +"<p>"
							+md.getComment()
							+"</p>"; 
			
				switch( md.getType()){
					case PIC: 
						break;
					case MAP:
						break;
				case SOUND:
					break;
				case VIDEO:
					break;
				default:
					break;
				 
				}
			}
		}
		
	}
	
	return rt;
}*/
/*
 * create the foomark html file content
 */
public void GenFootmark(boolean byForce,String roadbook){ 
	 
	 File myFile = new File(getFootMarkfileName());
	 FileOutputStream fOut =null;
		try {
		   if(!myFile.exists()){
			   myFile.createNewFile();
			   fOut = new FileOutputStream(myFile,false); //override			
			   fOut.write(roadbook.getBytes()); 
			   fOut.close();
		   }else  if(byForce){
			 fOut = new FileOutputStream(myFile,false); //override			
			 fOut.write(roadbook.getBytes()); 
		     fOut.close();
		   } 
	  	} catch (IOException e1) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e1, TAG);
		}
//		finally{
//			if(fOut!=null){
//				fOut.close();
//			}
		
 }
	
//读文件

public String getFootmark(){
	 String res=null;
		try {
		  
		    res = Utils.readSDFile(getFootMarkfileName());
			   
			  
		   }catch (IOException e1) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e1, TAG);
			}
		return res;
}
public String getFootMarkfileName(){
	
	File dir = new File(QiYouConstant.FOOTMARK_PATH);	
	if(!dir.exists()) dir.mkdirs();// 创建文件夹	
	
	return QiYouConstant.FOOTMARK_PATH+tb.getTrackId() +".html";
	  
}
/*
 * clear the footmark file
 */
public void TruncateFootMark(){
	File file = new File(getFootMarkfileName());
	if(file.exists()){
		try { 
			FileOutputStream  fOut = new FileOutputStream(file); //override		   
			fOut.write(new String().getBytes()); 
			fOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		  
		 
	}
}


public void setRoadBook(StringBuffer _roadBook) {
	this._roadBook = _roadBook;
}
/*
 * temporaly json wps for roadbear
 */
public StringBuffer getRdWpsJson() {
	return _rdWpsJson;
}
public void setRdWpsJson(StringBuffer sb) {
	 _rdWpsJson =sb;
}
 


/*public ArrayList<Waypoint_bean> getBearWps(){
	 return roadWps;
}*/


/*
 * generate _rdWpsJson
 * initialize roadbook 
 */
//public void setBearWps( CopyOnWriteArrayList<Waypoint_bean> wbs){
public void setBearWps(  ArrayList<Waypoint_bean> wbs){
	tb.setRoadWps(wbs);
	 
	  Gson gson = new Gson();	
		try{
			_rdWpsJson =new StringBuffer();
			_rdWpsJson.append(gson.toJson(wbs));	
		}catch(Exception e)
		{			
			Utils.logStackTrace(e, dTAG);
		}
		_roadBook = new StringBuffer();
}
public void finishRecording(){	
//	getTrackBean().setStatus(QiYouConstant.TRACK_STATUS_FINISHED); 
//    if(_startWp!=null)
//	setLastRoadBear(_startWp); 
	if(TrackStatus.FINISHED  == tb.getStatus())return; //already be finished.
	 try{
		 if(_maxDistWp!=null){
    	_maxDistWp.getWb().setTurnFlag(wpFlag.MAXR);
    	setLastRoadBear(_maxDistWp); 
    	// QLog.getLogger().d(dTAG,TAG+" set marR WP to the roadbear \n "+ _maxDistWp.toString());
    }
    
    if(_lastWp!=null){
    	_lastWp.getWb().setTurnFlag(wpFlag.END);
    	setLastRoadBear(_lastWp);
    	// QLog.getLogger().d(dTAG,TAG+" set last WP to the roadbear \n "+ _lastWp.toString());
    }
   
    	this.setBearWps(tb.getRoadWps());  //apply the maxR,Lastwp change to  the jsonBear and reset the roadbook
    }catch(Exception er){
    	Utils.logStackTrace(er, TAG);
    }
    
//    tb.setEndTime(System.currentTimeMillis());
  /*  long ttime=tb.getTotalTime()-(tb.getEndTime()-tb.getStartTime()); 
    if( ttime>0){
    	tb.setOffTime(tb.getOffTime()-ttime);
    }*/
}

public String getMaxRdistWpJson() {
	return _maxDistWpJson;
}

public void setMaxRdistWpJson(String maxDistWpJson) {
	_maxDistWpJson = maxDistWpJson;
	_maxDistWp = new Waypoint(maxDistWpJson);
	tb.setMaxDistWp(_maxDistWp);
	
}

public Waypoint getMaxDistWp() {
	return _maxDistWp;
}

public void setMaxDistWp(Waypoint maxDistWp) {
	_maxDistWp = maxDistWp;
}
private String summary ="";
public String getSummary(){
	if(tb.getType()==TrackType.GPX)return getGPXSummary();
	
	
	String startEndGeos = "";
	final String blankStr="";
	if(_startWp==null ||_lastWp ==null) return summary;
	
	int picCnt=0; 
	for(Waypoint_bean wb:tb.getMdWps()){
		if(wb!=null){ 
		 Media md =wb.getMedias().get(0);
		 if(md!=null && md.getType() == mediaType.PIC){
			 picCnt++;
		 }
		 
		}
	}
	
	String medias=String.format("%s运动过程没有记录拍摄照片。",blankStr);//；=String.format("\n拍照片%s张",);
	if(picCnt>0)
		medias =String.format("%s期间拍照片%s张。",blankStr,picCnt);
	String speedData=String.format("%s期间最高速度%.2f公里/每小时，平均运动速度%.2f公里/小时，全程均速%.2f公里/小时，",
									blankStr,
									tb.getTopSpeed(),
									tb.getAvs(),
									tb.getTavs()
								  );
	String overall=String.format("共%s%s。",									
									"运动了",//getTrackBean().getType().toCHString(),
									Utils.getFormatedDistance(tb.getDistance())
								 );
	if(_startWp.getWb().getGeo()!=null && _lastWp.getWb().getGeo()!=null )
		startEndGeos =String.format("    %s%s 从%s出发，%s 到达%s，",
						blankStr,
						Utils.getFormatedTimeMonthDay(tb.getStartTime()), 
						_startWp.getWb().getGeo().toString("，"),
						Utils.getFormatedTimeMonthDay(tb.getEndTime()),
						_lastWp.getWb().getGeo().toString(_startWp.getWb().getGeo(),"，") 
						);
	else{
		startEndGeos =String.format("    %s自%s至%s，",
					blankStr,
					Utils.getFormatedTimeMonthDay(tb.getStartTime()),
					Utils.getFormatedTimeMonthDay(tb.getEndTime())
					);
	}
	
	String distTime =String.format("历时%s，其中运动时间%s，",  
									Utils.getTimeCnt4Read(tb.getEndTime()- tb.getStartTime(), true),
									Utils.getTimeCnt4Read(tb.getSportTime(), true)									
								   );
	
	String eup =String.format("累计爬升%.0f米，累计下降%.0f米，",  
			tb.geteUpDist(),
			tb.geteDownDist()*-1									
		   );
	
	String cost =String.format("%s本次运动共消耗%.1f卡路里，继续加油~o~",blankStr,getCalBurn());//String.format("\n消耗%.0f大卡",tb.getCost());
	
    summary = Utils.getWeather()    		
			+ startEndGeos			
			+ distTime
			+ overall 		
			+ speedData		
			+ eup 
			+ medias
			+ cost
			;
 	
	return summary;
}

public String getGPXSummary(){
	String summary ="";
	String startEndGeos = "";
	final String blankStr="    ";
	if(_startWp==null ||_lastWp ==null) return summary;
	
//	int picCnt=0; 
//	for(Waypoint_bean wb:tb.getMdWps()){
//		if(wb!=null){ 
//		 Media md =wb.getMedias().get(0);
//		 if(md!=null && md.getType() == mediaType.PIC){
//			 picCnt++;
//		 }
//		 
//		}
//	}
//	
//	String medias=String.format("\n%s本次运动过程中没有拍照记录。",blankStr);//；=String.format("\n拍照片%s张",);
//	if(picCnt>0)
//		medias =String.format("\n%s期间拍照片%s张。",blankStr,picCnt);
	String speedData=isGpx()?"":String.format("\n%s期间最高速度%.2f公里/每小时，全程均速%.2f公里/小时。",
									blankStr,
									tb.getTopSpeed(),
//									tb.getAvs(),
									tb.getTavs()
								  );
	
	if(_startWp.getWb().getGeo()!=null && _lastWp.getWb().getGeo()!=null )
		startEndGeos =String.format("%s%s从%s出发，\n%s到达%s，",
						blankStr,
						Utils.getFormatedTime(tb.getStartTime()), 
						_startWp.getWb().getGeo().toString(","),
						Utils.getFormatedTime(tb.getEndTime()),
						_lastWp.getWb().getGeo().toString(",") 
						);
	else{
		startEndGeos =isGpx()?"":String.format("%s自%s至%s，",
					blankStr,
					Utils.getFormatedTime(tb.getStartTime()),
					Utils.getFormatedTime(tb.getEndTime())
					);
	}
	
	
	
	String creator =String.format("%s\n",   
            tb.getCreator()
//			Utils.getTimeCnt(tb.getSportTime())									
		   );
	
//	String cost =String.format("\n%s本次运动共消耗%.2f卡路里，继续加油~o~",blankStr,getCalBurn());//String.format("\n消耗%.0f大卡",tb.getCost());
//	if(isGpx()){
//		
//	}
	
    summary = Utils.getWeather()    
    		+(TextUtils.isEmpty(tb.getCreator())?"": creator)
			+ startEndGeos
			+ getGpxDistTime()	 
			+ speedData			
//			+ medias
//			+ cost
			;
 	
    
    
	return summary;
}

public String getGpxDistTime(){
/*	String overall=String.format("全程%s，",
			 Utils.getFormatedDistance(tb.getDistance())
		 );
	String distTime =String.format("预计历时%s。",   
            Utils.getTimeCnt4Read(tb.getEndTime()- tb.getStartTime(), true)
//			Utils.getTimeCnt(tb.getSportTime())									
		   );
	return overall +distTime;*/
	
	return String.format("全程%s，", Utils.getFormatedDistance(tb.getDistance()));
}

public StringBuffer getMdWpsJson() {
	return _mdWpsJson;
}

public void setMdWpsJson(String  mdWps ) {
	this._mdWpsJson.append(mdWps);
//	getWPS(new Gson(),mdWps);	
	
}
/*
 * generate _rdWpsJson
 * initialize roadbook 
 */
/*public void setMdWps( ArrayList<Waypoint_bean> wbs){
	tb.setRoadWps(wbs);
    _mdWpsJson =new StringBuffer(); 
	  Gson gson = new Gson();	
		try{ 
			_mdWpsJson.append(gson.toJson(wbs));	
		}catch(Exception e)
		{			
			Utils.logStackTrace(e, dTAG);
		}
		 
}*/
public float getCalBurn(){
	 return getCalBurn(tb.getType());
}

public float getCalBurn(TrackType type){
/*	float mets =Utils.getMets(type,tb.getAvs());
	float weight=QiYouConstant.PV_USER_WEIGHT;
	float hours =tb.getSportTime()/(3600f*1000f);
	float calories =mets*weight*(hours);
	float eUp =tb.getEsumUp() ;
	float mgh =0;
	if(calories>0 && eUp>0){
		 mgh =weight*9.8f*eUp;
		 mgh =mgh/4.184f;
		
	}
//	calories +=mgh;
	calories =calories>0?calories:0;*/
	float avs=tb.getAvs();
	avs=avs>0?avs:tb.getTavs();
	long sptime=tb.getSportTime();
	sptime=sptime>0?sptime:tb.getTotalTime();
	float calories=(float) Utils.getCalories(type,avs,sptime,tb.getEsumUp()); 
	
	tb.setBurn(calories);
	return calories; 
}

//public ArrayList<Waypoint_bean> roadWbs = new ArrayList<Waypoint_bean>();
//public String wps2json( CopyOnWriteArrayList<Waypoint_bean> wbs){
 public String wps2json(  ArrayList<Waypoint_bean> wbs){
	String json="";
	 Gson gson = new Gson();	
		try{ 
			json=gson.toJson(wbs);	
		}catch(Exception e)
		{			
			Utils.logStackTrace(e, dTAG);
		}
	return json;
}

public void setMd(String picName,Waypoint wp,mediaType mdType){
	
//	QLog.getLogger().d(dTAG, TAG+String.format(" begin to insert new mdiea,distanceis %s",distance)); 
	
   
	/*Waypoint  wp = new Waypoint();
	if(distance>0){//for map
		wp.getWb().setSumDist(distance);
	}
	else if( getLastWp()!=null){*/
	if(wp==null && getLastWp()!=null){
		wp = new Waypoint();
		wp.getWb().setLatitude( getLastWp().getWb().getLatitude());
		wp.getWb().setLongitude( getLastWp().getWb().getLongitude());
		wp.getWb().setTime( getLastWp().getWb().getTime());
		wp.getWb().setSumDist( getLastWp().getWb().getSumDist());
		wp.getWb().setSpeed( getLastWp().getWb().getSpeed());
		wp.getWb().setElevation( getLastWp().getWb().getElevation());
	}
	 
 	if(wp == null)wp = new Waypoint();
//	wp.getWb().getMedias().clear();//each md with a wb, //TODO: to update to let wb can have more medias, 
	
	boolean isExist=false;
	for(Media m: wp.getWb().getMedias()){
			if(m.getUri().equalsIgnoreCase(picName)){			
				isExist=true;
				break;
			}
		}
	if(!isExist){
		Media md = new Media(); 
		md.setTime(System.currentTimeMillis());
		md.setType(mdType); 
		md.setUri(picName); 
		wp.getWb().getMedias().add(md);	
	}
	 newMdWpsJson.append(wp.toJsonWp()+",");
//	activity.app.getRecordingTrack().setLastWp(wp);
//	activity.app.getRecordingTrack().getTrackBean().getMdWps().add(wp.getWb());
	tb.getMdWps().add(wp.getWb());
	
}

}
