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

import java.util.ArrayList;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.LineChart;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint.Align;
import android.view.View;

import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;

 
/**
 *X: distance
 *Y:time, speed
 */
 
public class DistKmSpeedChart extends AbstractChart {
	public static final String TAG ="com.qiyou.DistSpeedChart";
	public static final String dTAG ="com.qiyou";
	 
   	
  /**
   * Executes the chart demo.
   * 
   * @param context the context
   * @return the built intent
   */
  @Override
public Intent execute(Context context) {
	  
    buildChartData(); 
    Intent intent = null;
    try{
      intent = ChartFactory.getLineChartIntent(context, dataset, renderer, "速度-距离");
   
    }catch(Exception er)
    {
    	Utils.logStackTrace(er, TAG);
    }
     return intent;
  }
  
 /*
  *  (non-Javadoc)
  * @see com.qiyou.mb.android.ui.charts.AbstractChart#getChartView(android.content.Context)
  */
  @Override
 public View getChartView(Context context)
  {
	  View v = null;
	  try{
		  setFontSize(context);
		  buildChartData(); 
		  String[] types;  types= new String[] { BarChart.TYPE,BarChart.TYPE  }; 
		  v= ChartFactory.getCombinedXYChartView(context,  dataset,  renderer,types);
//		  v= ChartFactory.getLineChartView(context, dataset, renderer);
	   
	    }catch(Exception er)
	    {
	    	Utils.logStackTrace(er, TAG);
	    }
	  
	  return v;
	  
	 
  }
 
 @Override
 public void buildChartData(){
	    getTitles();
	    getXYvalues();
	    dataset = buildDataset(titles, xValues, yValues);
	    renderer = getRender(2, "", "距离（公里）", yTitle,true);
	    int left=  (int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *40);
	    int bottom =(int) (QiYouConstant.PV_INT_SCREEN_WIDTH/480f *30);
	    
	    
//	    renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right
	    renderer.setMargins(new int[] { 2, left,bottom, 0 });//top,left,bottom,right
	 
//	    renderer.setMargins(new int[] { 1, 80,60, 0 });//top,left,bottom,right
	    renderer.setYLabels(20);
	    int length = renderer.getSeriesRendererCount();
	    for (int i = 0; i < length; i++) {
	        SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
	        seriesRenderer.setDisplayChartValues(true);
	        seriesRenderer.setChartValuesTextSize(tFontSize);
//	        seriesRenderer.setChartValuesTextAlign(Align.CENTER);
//	        seriesRenderer.setDisplayChartValuesDistance(18);
//	        seriesRenderer.setChartValuesSpacing(5f);
	      }
 }
  
 
  void getTitles(){ 
	  if(trs.size()==0)return;
	  titles = new String[trs.size()*2];
	   int i=0;
	   String name="ID";
	   for(Track tr:trs){
		   if(tr ==null)continue;
		   name =name+tr.getTrackBean().getTrackId();
//		   name = String.valueOf((TextUtils.isEmpty(name)?tr.getTrackBean().getStartTime():name));
		  
		  titles[i]="每公里总用时" ;// 
		   i++;
		  
		   titles[i]="每公里运动用时";// 
		   i++;
	   }
 
  
  }
  
  String yTitle="配速（分钟）";//="时速--时间(分)";
//  String yTitle="";//="时速--时间(分)";
  double yTscale=1;
  double ySscale=1;
/* @Override
public double getMaxY(){
	  double maxYs =1;
	  double maxYt =1;
	  for(Track tr:trs){
		  if(tr ==null)continue;
//		  maxSportTime = getMaxTime();
		 
//		  maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY;
		  maxYs = tr.getTrackBean().getTopSpeed()>maxYs? tr.getTrackBean().getTopSpeed():maxYs;
//		  maxYt = getMaxTime()>maxYt? getMaxTime():maxYt;	  		  
	  } 
	  if(maxYs>maxYt*2){
//		  ySscale=  Math.round(maxYs/maxYt);
		  ySscale=   maxYs/maxYt ;
		  maxY = maxYs/ySscale ;
		  yTitle ="时速（x"+  Utils.round(ySscale,1) + "公里。小时）--时间（分）";
	  }
	  else if(maxYt>maxYs*2){
//    	  yTscale = Math.round(maxYt/maxYs);
		  yTscale =    maxYt/maxYs ;
		  maxY = maxYt/yTscale;
		  yTitle ="时速--时间（x"+ Utils.round(yTscale,1 )+"分）";
	  }else		  
		  maxY = maxYs>maxYt?maxYs:maxYt;
      QLog.getLogger().d(dTAG,TAG+" maxYs "+ maxYs +" maxYt: " +maxYt +" maxY: " +maxY  ); 
 	  QLog.getLogger().d(dTAG,TAG+" YsScale "+ ySscale +" yTscale: " +yTscale  ); 
	  return maxY;
	  
//	  return maxYs;
	 return maxY;
 }*/
 double maxY;

	public ArrayList<Track> getTrs() { 
		return trs;
	}

	void getXYvalues (){  
		minY=100;
		getMaxY();
	      xValues = new ArrayList<double[]>();		  
	       
		  XstepValue = 1000;//、、 getMaxDist()/Xcnt;
//		  XstepValue =  getMaxDist()/100;
//		  double[]  xD ; 
		  ArrayList<Double>  xD ;
		  ArrayList<Double>   xS ; 
	   
		  yValues = new ArrayList<double[]>();    
//		  double[]  yD; 
		  ArrayList<Double>  yT;  //total time
		  ArrayList<Double>   yS;  //sport time
		  
	  for(Track tr:trs){
		  if(tr==null)continue;
		  ArrayList<Waypoint_bean> al = new ArrayList<Waypoint_bean>();
		  
	         for(Waypoint_bean b:tr.getTrackBean().getTrkseg())
	         {
	         	if (null !=b)
	         		al.add(b);
	         }
	          
	         yT =new ArrayList<Double>(); 
	         yT.add(0,  0D);
	       yS =new ArrayList<Double>();
	       yS.add(0,  0D);
	       xD = new ArrayList<Double>();//[Xcnt+1];	       
		   xD.add(0,  0D);;
		   xS =new ArrayList<Double>();
		   xS.add(0,  0D);
	       double ttmS =0 ;  //step value for Speed  
//	       double ttmt =0 ;  //step value for time bar
	        
	        Waypoint_bean  wb;
//	        int j=0;  
//	        double k=0;
//	        double asp =0.0;  //step average Speed
//	        long trStartTime;
//	        double lwb;
	        double xvalue=0;
	        double yt;
	        double ys;
//	        long lastSpTime=0;
	        long lastSpTime= 0;
	        long lastTotalTime=tr.getTrackBean().getStartTime();
	        double xStepvalue= 1000;
	        minY=-201.11;
//	        for(Waypoint_bean wb:al){
	        for(int i=0;i<al.size();i++){
	        	wb = al.get(i); 
	        	if(wb.getSumDist()==0 ||i>0 &&al.get(i).getTime()< al.get(i-1).getTime()){
//	        		QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped.");
	        		continue;
	        	}
//	        	wb = al.get(i); 
//	        	trStartTime =tr.getTrackBean().getStartTime();
//	        	lwb = i>0?al.get(i-1).getDistance():0;
//	        	lwb = wb.getDistance();
//	        	xvalue = (int)(wb.getSumDist()/1000);
	        	xvalue =Math.round(wb.getSumDist()/1000);
	            ttmS+=wb.getDistance();
//	            ttmt+=wb.getDistance();
//	            yt=(wb.getTime()-trStartTime)/1000.0/60.0/yTscale;
//	            yt=(wb.getSportTime())/1000.0/60.0/yTscale;
//	            yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0/yTscale;
//	            lastSpTime = wb.getSportTime();
//	          asp +=wb.getSpeed()/ySscale;
//	          QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale  ); 
//	          k++; 
	         
//		          if(ttmS>=xStepvalue || i==al.size()-1  ){  // filter x distance data to not show all.                 //bar, minutes/km
	          if(xvalue>0 && wb.getKmflag()>0 ||ttmS>=xStepvalue|| i==al.size()-1  ){
//		        		  yt=(wb.getSportTime()-lastSpTime)/1000.0/60.0;
	        	          yt=(wb.getTime()-lastTotalTime)/1000.0/60.0;
	        	          ys=(wb.getSportTime()-lastSpTime)/1000.0/60.0;
//		        		  QLog.getLogger().d(dTAG,TAG+" lastSpTime "+ lastSpTime + ",wb.getSportTime() "+wb.getSportTime()   );
				        	
		        		  lastSpTime = wb.getSportTime();
		        		  lastTotalTime = wb.getTime();
		        		  QLog.getLogger().d(dTAG,"--------------------------------------- wb.getSumDist(): " +wb.getSumDist()  );
		        		  QLog.getLogger().d(dTAG,"i: "+ i +" xvalue: " +xvalue  );
		        		  QLog.getLogger().d(dTAG,"wb.getKmflag() "   +wb.getKmflag()  );
		        		  QLog.getLogger().d(dTAG,"yt "   +yt  );
//		        		  QLog.getLogger().d(dTAG,TAG+" yt "+ yt + ", wb.getSpeed()/ySscale "+wb.getSpeed()/ySscale+ "; YsScale "+ ySscale +" yTscale: " +yTscale  );
		        			
//		        		  xvalue=wb.getKmflag()>0?wb.getKmflag():xvalue; 
		        			
		        		  xD.add(xvalue);//	        		 
			        	  yT.add(Utils.round(yt,1));
			        	  
			        	  xS.add(xvalue); 
			        	  yS.add(Utils.round(ys,1)  );
			        	  
//			        	  j=0;
			        	  if(minY==-201.11)minY= yt;
			        	  maxY=maxY>ys?maxY:ys;
			        	  minY =minY > yt ?yt:minY;
			        	  ttmS =0;
	//		        	  xS.add(xvalue); 
	//	        		  yS.add( asp/(k+0.00) );
	//	        		  maxY=maxY> asp/(k+0.00)?maxY: asp/(k+0.00);
	//	        		  asp=0.0;
	//	        		  k=0;
	//		        	    
		        	  } 
	            

	          
	        }
	        
		       xD.add(xvalue+0.1);//	        		 
		      yT.add(0d); 
	      	  xS.add(xvalue+0.1); 
	      	  yS.add(0d ); 
      	  
//	        minY=minY>3?minY:3;
//	        maxY=maxY<5*minY?maxY:5*minY;
	        float avkm=tr.getTrackBean().getSportTime()/60/1000/(tr.getTrackBean().getDistance()/1000);
	       
	        QLog.getLogger().d(dTAG,"total minutes: "+   tr.getTrackBean().getSportTime()/60/1000  ); 
  		    QLog.getLogger().d(dTAG,"distance km: "+ tr.getTrackBean().getDistance()/1000 );
  		    QLog.getLogger().d(dTAG,"avkm: "+Math.round(avkm)  );
  		    QLog.getLogger().d(dTAG,"maxY: "+ maxY  );
  		    
	        maxY=maxY<avkm*3?maxY*1.1:avkm*3;
	        QLog.getLogger().d(dTAG,"maxY: "+ maxY  );
	         minY=0;  
	 	       
	        yValues.add( getDv(yT) );   
		    xValues.add(getDv(xD,true)); //total time4
	      
		      yValues.add(getDv(yS  )); 
	 	    xValues.add(getDv(xS,true)); //sport time 	  
		  
 	  	}  
	  }

	@Override
	public double getMaxY() {
		// TODO Auto-generated method stub
		return maxY;
	}
}
	    
  


