package com.qiyou.mb.android.service;

import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.wpFlag;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

public class TrackPlaybackService extends IntentService { 

	public final static String TAG="com.qiyou.LOCATION_PLAYBACK_SERVICE";
	public static final String dTAG ="com.qiyou";
	protected QiYouApplication app;
	public TrackPlaybackService( ) {
		super(TAG);
		// TODO Auto-generated constructor stub
		 app =(QiYouApplication)this.getApplication(); 
		 
	}
	public TrackPlaybackService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
		
	}
	 @Override
	public void onCreate() {
		    super.onCreate();
		    app =(QiYouApplication)this.getApplication(); 
	 }
	 private int trackId =-1;
//	private int gps_span =2000;
	private Intent serviceIntent ;
	private HashMap<Float,Waypoint_bean> bears;
	@Override
	protected void onHandleIntent(Intent intent) {

		// TODO Auto-generated method stub

		 String key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID;
		  
		
		 
		    //get specified track by id
		    if (intent.hasExtra(key)) {
		    	trackId = intent.getExtras().getInt(key);
		    }
		    
		    if(app.playBackTrackId != trackId) return; 
		    
		    if(QiYouConstant.PLAYBACK_CAN_RECORD) {
		    	serviceIntent = new Intent(this, LocationService.class);
		    }
		    
		  
		    
//		   if(trackId<=0) return; 	
		
//		    Intent sintent = new Intent(this,SplashActivity.class);
//		    sintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//	    	this.startActivity(sintent);
		    
		/*while( app.getCurrentTrack().getTrackBean().getTrackId() != Integer.valueOf(trackId)){
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				} 
		}*/
		 
		getCurrentPlayBackTrackWps(); 
//	    gps_span=app.currentTrack.getTrackBean().getGpsSpan();
//        gps_span =gps_span<=0?QiYouConstant.MAX_GPS_SPAN:gps_span;
	
	}
	
	void getCurrentPlayBackTrackWps() {	
		
		
		//TODO: replace the sleep with a started activity/fragment for waiting db.
		while(app.getCurrentTrack().getTrackBean().getTrackId() !=app.playBackTrackId
				&&
				app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId)
		{
			try {
				Thread.sleep(100);
//			      app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(app.playBackTrackId)),
//			    		  app.getCurrentTrack().getTrackBean().getSvrNumber() ==app.playBackTrackId
//			    		  );
				app.currentTrack =app.getTrackCache().get(Integer.valueOf(app.playBackTrackId));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
//		 long bfdbTime = System.currentTimeMillis();
		/* CopyOnWriteArrayList<Waypoint_bean> al = new CopyOnWriteArrayList<Waypoint_bean>();
        for(Waypoint_bean b:app.getCurrentTrack().getTrackBean().getTrkseg())
        {
        	if (null !=b)
        		al.add(b);
        }

		Collections.sort(al, new SortByTime());
		app.getCurrentTrack().getTrackBean().setTrksegs(al);*/
		// QLog.getLogger().d(dTAG,TAG+" Sort the wps spend time " +String.valueOf((System.currentTimeMillis()-bfdbTime)) );
		   
		
		
		bears= new HashMap<Float,Waypoint_bean>();
//		int i=0;
//		Waypoint_bean nextWb;
//		/*CopyOnWriteArrayList<Waypoint_bean> al2=app.getCurrentTrack().getTrackBean().getRoadWps();*/
		 ArrayList<Waypoint_bean> al2=app.getCurrentTrack().getTrackBean().getRoadWps();
		
		for(Waypoint_bean wb:al2){
//			i++;
			if(wb==null)return;
			 
//			if(	app.getCurrentTrack().isLushu()){
//				if(i<al2.size()){
//					nextWb=al2.get(i);
//					if(nextWb!=null &&!nextWb.getTurnFlag().toCHString().equalsIgnoreCase(wpFlag.CUST.toCHString()))
//						bears.put(wb.getSumDist(), nextWb);
//				 } 
//			}else{
				bears.put(wb.getSumDist(), wb);
//			}
				
		
		}
//		CopyOnWriteArrayList<Waypoint_bean> al = new CopyOnWriteArrayList<Waypoint_bean>()
		sendLocations(app.getCurrentTrack().getTrackBean().getTrkseg() );
//		sendLocations(al );		 
	
	} 
	int target=-1;
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
	/*void sendLocations(CopyOnWriteArrayList<Waypoint_bean> al){*/
	void sendLocations( ArrayList<Waypoint_bean> al){
		Location loc;		
//		long last_old_time =0;
//		long last_new_time =0;
//		Track tr1 = new Track(null,jsonWps);
//		 ArrayList<Waypoint> al =tr1.getTrackBean().getTrkseg();
		
		//TODO: find some way to terminate the loop when the playback quit.
//		long startTime =System.currentTimeMillis();
 		int i = 0;
//		QLog.getLogger().d(dTAG,TAG+" size of wps to playback: " +al.size());
		Long lasttime =0L;  //to remove
		float lastDist = 0;
		float maxR=0;
		float lastspdDist = 0;
//		 synchronized(al)
		 {
			 
			/*String mocLocationProvider ="mockLp";
			if(QiYouConstant.DEVELOPER_MODE &&app.lm.getProvider(mocLocationProvider)==null){
				QLog.getLogger().d(dTAG, "set mock test provider");
				app.lm.addTestProvider(mocLocationProvider, false, false,
		                    false, false, true, true, true, 0, 5);
				app.lm.setTestProviderEnabled(mocLocationProvider, true);
			}*/
			
//			 QiYouConstant.PLAYBACK_TIME_INTERVAL =2000;
			 
			 for(Waypoint_bean wb:al) { 
				 
				  if(!app.playBack ||app.playBackStopped)break;
				  
					if(app.playBackTrackId != trackId
							|| app.getCurrentTrack().getTrackBean().getTrackId()!=app.playBackTrackId 
								&& app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId){
							// QLog.getLogger().d(dTAG,TAG+" playBackTrackId != trackId ， retart the playback service. ");
							 app.startPlayBackService(app.playBackTrackId);
							 break;
							 }   
						if(wb ==null)continue;
						 
						//back to target
						if( app.playProgressTarget>-1 && wb.getSumDist()> app.playProgressTarget){							
							target=app.playProgressTarget;
							app.playProgressTarget=-1;
							sendLocations(al);
							return;
						  }
						
						
						if(wb.getSumDist() < target){							
							continue;
						}
						//	forward to target
						if(  wb.getSumDist()< app.playProgressTarget){
							target=app.playProgressTarget;
							app.playProgressTarget=-1;
							continue;
						}
						
						
						if (lasttime ==0L) lasttime =wb.getTime(); 
						if (lastDist ==0 ){
							lastDist = wb.getSumDist();
						}
						if(wb.getTime()< lasttime || wb.getSumDist() < lastDist  ){
							 // QLog.getLogger().d(dTAG,TAG+" get bad duplicated wp:"+ String.valueOf(wb.getTime() ));
							 continue; 
						 }
						
					
						 
						
						loc = new Location(LocationManager.GPS_PROVIDER);			
//						loc = new Location("playback");
						loc.setAltitude(wb.getElevation());
						loc.setLatitude(wb.getLatitude());
						loc.setLongitude(wb.getLongitude());
						loc.setSpeed( wb.getSpeed()/3.6f) ;
						Bundle bd = new Bundle(); 						
						bd.putLong("wptime",wb.getTime());
						bd.putLong("sptime",wb.getSportTime());
						bd.putLong("pausetime",wb.getPauseTime());
						bd.putLong("offtime",wb.getOfftime());
						bd.putFloat("dist",wb.getSumDist());
						
						double r=Utils.getDistanceFromXtoY(wb.getLatitude(),wb.getLongitude(), 
								app.getCurrentTrack().getStartWp().getWb().getLatitude(), app.getCurrentTrack().getStartWp().getWb().getLongitude());
						maxR =(float) (maxR<r?r:maxR); 
						
						bd.putFloat("maxR",maxR/1000f);
						
						 if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL<2 && wb.getTurnFlag()!=wpFlag.NORMAL &&!app.isNaving){ 
//						if(QiYouConstant.CAN_SPEAK && wb.getTurnFlag()!=wpFlag.NORMAL &&!app.isNaving){
							 Waypoint_bean bear =bears.get(Float.valueOf(wb.getSumDist()));
							 if(bear!=null){
								 boolean isNull =bear.getGeo()==null;
								/* String geo =isNull?"": ",\n前方到达 "+bear.getGeo().toString(",");
								 String msg=bear.getRoadBook()+bear.getComment()+geo;*/
								 String geo =isNull?"": "到达 "+bear.getGeo().toString(",")+"\n， ";
								 String msg=geo+bear.getRoadBook()+bear.getComment();
								 bd.putString(QiYouConstant.NEW_NAVIFO_MSG, msg);
								 loc.setExtras(bd); 
								 app.naviUI(loc, msg);
								 msg =QiYouConstant.PV_INT_NAVI_SPEAK_MODEL==0?msg:geo;
								 
								 if (lastspdDist != lastDist){
									 app.speech( msg,1);
								 }
								
								 lastspdDist = lastDist;
								 // QLog.getLogger().d(dTAG, TAG+" wb.getRoadBook(): "+wb.getRoadBook() );
							 }
						 } 
							
						 loc.setExtras(bd);
						
						
						
						
						loc.setTime(wb.getTime());						
//						QLog.getLogger().d(dTAG, TAG+" wb.getTime(): "+wb.getTime() );
						if(app.currentTrack.getTrackBean().getType()!=TrackType.GPX)	
							loc.setAccuracy( wb.getAccuracy() );
						 
						 
						if(app.currentTrack.getTrackBean().getType()!=TrackType.GPX || wb.getBearing()>0)
							loc.setBearing( wb.getBearing() );
						
		 
						
					 loc.setTime(System.currentTimeMillis()); 
					
					 if(QiYouConstant.PLAYBACK_CAN_RECORD) {
						 serviceIntent.putExtra(LocationManager.KEY_LOCATION_CHANGED, loc); 
						 startService(serviceIntent);
					 }
					 
				     lasttime =wb.getTime();
				     lastDist = wb.getSumDist();
					 
					 
 					 i++;
// 					 QLog.getLogger().d(dTAG,TAG+" sent location No. " + i +" of "+al.size());
//					 QLog.getLogger().d(dTAG,TAG+" wb detail, lat:" + wb.getLatitude()+",lon:" +wb.getLatitude() +",speed:"+wb.getSpeed()  );
//					 
					 
					
					 try {
						  if(!app.playBack ||app.playBackStopped)break;
						
						 //TODO: CHECK WHY STUCK HERE WHEN CHANGE CURRENT PLAY BACK TRACK.
						   int totalSleep =0;
						  while(i>1 && totalSleep<6000 &&(app.playbackPaused ||QiYouConstant.CAN_SPEAK && app.isSpeaking())){
						   
//			 					 QLog.getLogger().d(dTAG,String.format(" is speeaking ?%s, total sleep  %s",QiYouConstant.CAN_SPEAK && app.isSpeaking(), totalSleep));
			 				 
			 					  Thread.sleep(500);
			 					 totalSleep+=500;
							  if( app.playBackStopped){
								  break;
							  }
						   }
						   
						   Thread.sleep(QiYouConstant.PLAYBACK_TIME_INTERVAL);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					   
	 			
					 
					 Intent broadcastIntent = new Intent();
						broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);
						broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);					 
					    broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc);
					 sendBroadcast(broadcastIntent);
					 if(QiYouConstant.IS_TEST_NAV)
						 app.lastNaviLocation= loc;
					 
					
							 
					 
					 
					 
				/*	 
					 if(QiYouConstant.DEVELOPER_MODE){
						 Location mockLocation = new Location(mocLocationProvider); // a string
						 mockLocation.setLatitude(wb.getLatitude());  // double 
						 mockLocation.setLongitude(wb.getLongitude()); 
						 mockLocation.setAltitude(wb.getElevation()); 
						 mockLocation.setTime(System.currentTimeMillis());
						 mockLocation.setAccuracy(wb.getAccuracy()>0?wb.getAccuracy():3f);  
						 mockLocation.setBearing(wb.getBearing()>0?wb.getBearing():1);
 						 mockLocation.setElapsedRealtimeNanos(android.os.SystemClock.elapsedRealtimeNanos());
						 
						 app.lm.setTestProviderLocation( mocLocationProvider, mockLocation);  
					 }*/
				}
		 }
		
		if(app.playBackTrackId != trackId 
				|| app.getCurrentTrack().getTrackBean().getTrackId()!=app.playBackTrackId
					&& app.getCurrentTrack().getTrackBean().getSvrNumber() !=app.playBackTrackId ){
			 app.startPlayBackService(app.playBackTrackId);
			}else
			{
				 // QLog.getLogger().d(dTAG,TAG+" playBackTrackId,trackId "+app.playBackTrackId+" , "+ trackId );
// 				app.playBack =false;//playback was over.
				 app.playBackStopped=true;
				// QLog.getLogger().d(dTAG,TAG+"  track  "+trackId+" play back is done.");
				 loc =new Location("playback");
				loc.setSpeed(-1);
				 Intent broadcastIntent = new Intent();
					broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);
					broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);					 
				    broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, loc);
				 sendBroadcast(broadcastIntent);
			}
		 
	 }
	
	
	@Override
	public void onDestroy() {

//		 QLog.getLogger().d(dTAG,TAG + " Services onDestory");
//		 Log.i(dTAG,TAG + " Services onDestory");

		// // isStop=true;//即使service销毁线程也不会停止，所以这里通过设置isStop来停止线程
		// // QLog.getLogger().d(TAG," save app.sumPaused "+app.sumPaused );
		// QLog.getLogger().d(TAG," save app.sumOfftime: "+app.sumOfftime );
		// QLog.getLogger().d(TAG,"---------app.sumPause loop----------------------------" );
		 
		super.onDestroy();

	}
	 
	
   }


 class SortByTime implements Comparator<Waypoint_bean> {
	 @Override
	public int compare(Waypoint_bean wb1, Waypoint_bean wb2) { 
	  if (wb1.getTime() > wb2.getTime())
	   return 1;
	  return 0;
	 }
	}
	 
	
 
