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

import java.util.ArrayList;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

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

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;

/**
 * Average temperature demo chart.
 */
public class DistanceSpeedBarChart extends AbstractChart {
	public static final String TAG ="com.qiyou.DistanceChart";
	public static final String dTAG ="com.qiyou";
	String[] Dtitles ;
	 int[] colors ;
	String[] Stitles ;
    List<double[]> xDvalues ;  
    List<double[]> yDvalues ;
    List<double[]> xSvalues ;  
    List<double[]> ySvalues ;
//    XYMultipleSeriesDataset Ddataset;
//    XYMultipleSeriesRenderer  renderer;
//    XYMultipleSeriesDataset Sdataset;
    
   	
  /**
   * 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,
        "距离-时间");
      ChartFactory.getLineChartView(context,  dataset,  renderer);
    }catch(Exception er)
    {
    	Utils.logStackTrace(er, TAG);
    }
     return intent;
  }
  
  @Override
 public View getChartView(Context context)
  {
	  buildChartData(); 
	   return ChartFactory.getLineChartView(context, dataset,  renderer);
  }
 
 
 public View getChartBarView(Context context)
  {
	  buildBarChartData();  
	  
	  String[] types;
	  
	  if(Dtitles.length>1)	  
		  types= new String[] { LineChart.TYPE, LineChart.TYPE, BarChart.TYPE , BarChart.TYPE };
	  else
		  types= new String[] { LineChart.TYPE,  BarChart.TYPE  }; 
	 
     return ChartFactory.getCombinedXYChartView(context,  dataset,  renderer,types);
//	  return null;
  }
 @Override
public void buildChartData(){
	    getTitles();
	    getXYvalues();
	     dataset = buildDataset(Dtitles, xDvalues, yDvalues);
	     renderer = getRender(2,"距离-速度-时间 ", "时间(分钟)", "距离(公里)/速度(公里/小时)"); 
 }
 
 
 void buildBarChartData(){
	 buildChartData();
//	 Sdataset = buildDataset(Stitles, xSvalues, ySvalues);
	 updateRender();
	 addXYSeries( dataset, Stitles, xSvalues, ySvalues, 0);
//	 Drenderer.addSeriesRenderer(renderer)
	 
	 
	 
	  
}

 
 
 void updateRender()
 {
	    buildBarRenderer(renderer,colors);
 }
 
  
  private int Xcnt =30;
  private double XstepValue;
//  private ArrayList<Track> trs = new ArrayList<Track>();  
  
//  
  XYMultipleSeriesRenderer getRender()
  { 
	  
 	    int[] allColors = new int[] { Color.BLUE, Color.GREEN, Color.CYAN, Color.YELLOW  };
 	    PointStyle[] allStyles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND,
 	        PointStyle.TRIANGLE, PointStyle.SQUARE };
	    

	    colors = new int[trs.size()]  ;
	    PointStyle[] styles = new PointStyle[trs.size()]  ;
	    
	 
	    for(int i=0;i<trs.size();i++){ 
	    	 colors[i]=  allColors[i];
			 styles[i]=allStyles[i];
	    } 
	    
	    XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
	    int length = renderer.getSeriesRendererCount();
	    for (int i = 0; i < length; i++) {
	      ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
	    }
	    
//	    setChartSettings(renderer,"Distance - time chart", "Time", "Distance", 0.5, 12.5, -10, 40,
//		        Color.LTGRAY, Color.LTGRAY);
	
	    
	    setChartSettings(renderer, "距离-速度-时间 ", "时间(分钟)", "距离(公里)/速度(公里/小时)", 0, getMaxTime(), 0, getMaxY()*1.1,
		        Color.LTGRAY, Color.LTGRAY);
	    
	    renderer.setInScroll(true); //http://zhirong.iteye.com/blog/1629781
	    
//	    renderer.setXLabels((int) getMaxTime()); 
//	    renderer.setYLabels((int) getMaxDist());
	    renderer.setXLabels(10);
	    renderer.setYLabels(10);
	    renderer.setShowGrid(true);
	    renderer.setXLabelsAlign(Align.RIGHT);
	    renderer.setYLabelsAlign(Align.RIGHT);
	    renderer.setZoomButtonsVisible(true);
//	    renderer.setShowAxes(true);
	    renderer.setShowLegend(true);
//	    renderer.setPanLimits(new double[] { 0,  getMaxTime()*2, 0, getMaxDist()*2 });
//	    renderer.setZoomLimits(new double[] { 0,  getMaxTime()/2, 0, getMaxDist()/2 });
	    renderer.setPanLimits(new double[] { 0,  getMaxTime(), 0, getMaxY() });
	    renderer.setZoomLimits(new double[] { 0,  getMaxTime(), 0, getMaxY()});
 
	    
	    return renderer;
  }
//  
  
  void getTitles(){ 
	  if(trs.size()==0)return;
	  Dtitles = new String[trs.size()];
	  Stitles = new String[trs.size()];
	   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));
		   Dtitles[i] =name + "距离";		   
		   Stitles[i] =name + "速度";
		   i++;
		   
	   }
//     if(titles.length > trs.size())
//	  {
//		  String[] tmp =new String[trs.size()] ;
//		  int i=0;
//		  for(Track tr:trs){			 
//			  i++;
//			  if(tr ==null)continue;			  
//			  tmp[i]=titles[i];			  
//		  }
//		  titles =tmp;
		  
		  
//	  }
	  
// 	   titles = new String[] { "Crete","Corfu"};//, "Corfu", "Thassos"};
//	   return titles;
  
  }
  
 
  
 @Override
public double getMaxY(){
	  double maxY =0;
	  for(Track tr:trs){
		  if(tr ==null)continue;
//		  maxSportTime = tr.getTrackBean().getSportTime()>maxSportTime? tr.getTrackBean().getSportTime():maxSportTime;
		 
		  maxY = tr.getTrackBean().getDistance()/1000.0>maxY? tr.getTrackBean().getDistance()/1000.0:maxY;
		  maxY = tr.getTrackBean().getTopSpeed()>maxY? tr.getTrackBean().getTopSpeed():maxY;
	  } 
	  
	  return maxY;
 }
 

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

 
void getXYvalues(){ 
	   
	   
	   
	      xDvalues = new ArrayList<double[]>();
	      xSvalues = new ArrayList<double[]>();
		  
		  double maxSportTime = getMaxTime(); 
		  XstepValue = maxSportTime/Xcnt;
		  double[]  xD ; 
		  double[]  xS ; 
	   
		  yDvalues = new ArrayList<double[]>();
		  ySvalues = new ArrayList<double[]>();
		  double[]  yD;  
		  double[]  yS;  
		  
	  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);
	         }
	         
//	       Yvalues = new double[(int) (al.size()/Xcnt)];
	       yD = new double[Xcnt];
	       yD[0] =0;
	       yS = new double[Xcnt];
	       yS[0] =0;
	       xD = new double[Xcnt+1];	       
		   xD[0] =0;
		   xS = new double[Xcnt+1];
		   xS[0] =0;
	       float ttm =0 ;  
	       long tm=0;
	       double xvalue=0;
	        Waypoint_bean  wb;
	        int j=1;  
//	        for(Waypoint_bean wb:al){
	        for(int i=0;i<al.size();i++){
	        	if(i>0 && al.get(i).getTime()< al.get(i-1).getTime()){
	        		QLog.getLogger().d(dTAG,TAG +" Duplicated WB, dropped.");
	        		continue;
	        	}
	        	wb = al.get(i);
	        	long lwb = i>0?al.get(i-1).getTime():tr.getTrackBean().getStartTime();
	        	xvalue = (wb.getTime() -tr.getTrackBean().getStartTime())/1000.0/60.0; 
	           tm =	wb.getTime() -lwb;//how much time till the wp
	          ttm+=tm;
//	          QLog.getLogger().d(dTAG,"i: "+ i +", ttm is: "+ ttm +",XstepValue is: "+XstepValue +", j: " +j);
	          
	          if(ttm >=XstepValue*1000*60 && j<Xcnt || tr.getTrackBean().getTopSpeed() == wb.getSpeed()){
	        	  
	        	 
	        		  xD[j] =XstepValue*j;
	        		  yD[j] =  wb.getSumDist()/1000.0;
	        	  
	        	  xS[j] =XstepValue*j;
	        	  yS[j] =  wb.getSpeed();
	        	  ttm =0;
	        	  j++;
	          }else if(i==al.size()-1 && j<Xcnt){
	        	  xD[j] = xvalue;	        	  
	        	  yD[j] =(int) al.get(i).getSumDist()/1000.0;
	        	  
	        	  xS[j] = xvalue;
	        	  yS[j] =  wb.getSpeed();
	        	 
	          }   
//	          if(tr.getTrackBean().getTopSpeed() == wb.getSpeed()){
//	        	  
//	          }
	          
	          
	        } 
//	        //fill the left blank points to be the track distance.
//	          for(int i=j+1;i<Xcnt;i++){
//	        	  y[i] = y[j];
//	          }
	          
	          if(j<Xcnt)j++;
	          double[]  xDv = new double[j]; 
	          double[]  yDv = new double[j]; 
	          double[]  xSv = new double[j];
	          
	          for(int i=0;i<j;i++){
	        	  xSv[i] =xS[i]; 
	        	  if(i%2==0 || i==j-1){
	        		  xDv[i] = xD[i];
	        		  yDv[i] = yD[i];
	        	  }
	        	  maxXvalue =maxXvalue< xSv[i]? xSv[i]:maxXvalue; 
	        	  
	        	  
	          }
//	     	 y.add(Yv);    
	          
	       yDvalues.add(yDv);   
	       ySvalues.add(yS);
	       xDvalues.add(xDv); //distance
	       xSvalues.add(xSv); //speed
	      
		  
   	  }  

	   } 
 
 
//	public void setTrs(ArrayList<Track> trs) {
//	
//		if(trs.size()>4) 
//		{ 	
//			this.trs.clear();
//			 for(int i =0;i<=3;i++){
//				 this.trs.add(trs.get(i));
//			 }
//		}else
//	 this.trs = trs; 
//		 
//	}
// 
// 
//     List<double[]> getX(){
//	  
//	  List<double[]> x = new ArrayList<double[]>();
//	  
//	  double maxSportTime = getMaxTime(); 
//	  XstepValue = maxSportTime/Xcnt;
////	  XstepValue = maxSportTime/Xcnt;
//	  double[]  Xvalues = new double[Xcnt];
//	  
////	  for (int i = 0; i <Xcnt; i++) {
//////		  Xvalues.add(XstepValue*i );
////		  Xvalues[i] =XstepValue*i;
////	    }
//	  
//	  for (int i = 0; i < trs.size(); i++) {
//		  
//		  for (int j = 0; j <Xcnt; j++) {
//			  
//			  Xvalues[j] =XstepValue*j;
//		    }
//	      x.add(Xvalues);
//	    }
//	  
//	  
////	  x = new ArrayList<double[]>();
////	    for (int i = 0; i < trs.size(); i++) {
////	      x.add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
////	    }
//	  return x;
//  }


	
	/*
	 * build y data
	 * distance
	 
    List<double[]> getY(){
	
    	
    	
//       [135.8497314453125, 35.55116271972656, 31.631629943847656, 31.566986083984375, 39.92951965332031, 17.68587875366211, 3.73708176612854, 22.835655212402344, 17.93094825744629,
//    	   9.902849197387695, 23.028324127197266, 134.236328125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    	List<double[]> y = new ArrayList<double[]>();		   
     
    	 double[]  Yvalues;  
          
    	  for(Track tr:trs){
    		  ArrayList<Waypoint_bean> al = new ArrayList<Waypoint_bean>();
    	         for(Waypoint_bean b:tr.getTrackBean().getTrkseg())
    	         {
    	         	if (null !=b)
    	         		al.add(b);
    	         }
    	         
//    	       Yvalues = new double[(int) (al.size()/Xcnt)];
    	       Yvalues = new double[Xcnt];
    	       Yvalues[0] =0;
    	          float ttm =0 ;  
    	          long tm=0;
    	          Waypoint_bean  wb;
    	        int j=1;  
//    	        for(Waypoint_bean wb:al){
    	        for(int i=0;i<al.size();i++){
    	        	wb = al.get(i);
    	        	long lwb = i>0?al.get(i-1).getTime():tr.getTrackBean().getStartTime();
    	        	 
    	           tm =	wb.getTime() -lwb;//how much time till the wp
    	          ttm+=tm;
    	          if(ttm >=XstepValue*1000*60 && j<Xcnt){
    	        	  Yvalues[j] =(int) wb.getSumDist()/1000.0;
    	        	  ttm =0;
    	        	  j++;
    	          }else if(i==al.size()-1 && j<Xcnt){
    	        	  Yvalues[j] =(int) al.get(i).getSumDist()/1000.0;
    	          }    	         
    	          
    	        } 
    	        //fill the left blank points to be the track distance.
    	          for(int i=j+1;i<Xcnt;i++){
    	        	  Yvalues[i] = Yvalues[j];
    	          }
    	          
//    	          j++;
//    	          double[]  Yv = new double[j]; 
//    	          
//    	          for(int i=0;i<j;i++){
//    	        	  Yv[i] =Yvalues[i];
//    	          }
//    	     	 y.add(Yv);    
    	          
    		 y.add(Yvalues);
    		  
       	  }  
    	  
    	  
    	  
//    	  y = new ArrayList<double[]>();
//    	    y.add(new double[] { 12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2,
//    	        13.9 });
//    	    y.add(new double[] { 10, 10, 12, 15, 20, 24, 26, 26, 23, 18, 14, 11 });
//    	    y.add(new double[] { 5, 5.3, 8, 12, 17, 22, 24.2, 24, 19, 15, 9, 6 });
//    	    y.add(new double[] { 9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13, 10 });
    	    
		   return y;
	   }
    
    */
  
  

}
