package com.qiyou.mb.android.service;

import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.log.QLog;

/*
 * Monitor the locaiton GPS signal, while the signal continues the service will exit.
 */
public class LocationMornitorService extends IntentService { 

	public final static String TAG="com.qiyou.MORNITOR_LOCATION_SERVICE";
	public static final String dTAG ="com.qiyou";
	protected QiYouApplication app;
    long update_interval = 0;
	long logtime;
	
//	Location location ;
	public LocationMornitorService( ) {
		super(TAG);
		// TODO Auto-generated constructor stub
//		 app =(QiYouApplication)this.getApplication(); 
		
	}
	public LocationMornitorService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
		
	}
	
	 @Override
	public void onCreate() {
		    super.onCreate();
		    app =(QiYouApplication)this.getApplication();
		    update_interval = app.getGPS_REQUEST_SPAN()/2*4;
		    printAppStartTime();
			QLog.getLogger().d(dTAG,TAG+" Start the service for monitoring GPS status.   time: "+ System.currentTimeMillis() );
			
	 }
	 
	@Override
	protected void onHandleIntent(Intent intent) { 
		 if(!app.canSendLocation2UI) return; 
		 if(app.playBack || app.getRecordingTrack().getTrackBean().getStatus()!=TrackStatus.RECORDING)return;
//		if(!intent.hasExtra(QiYouConstant.NEW_LOCATION))return;
//		location =(Location)intent.getExtras().get(QiYouConstant.NEW_LOCATION);
		monitorLocation();   
		   
	}
	 
//	long lastLocTime=0;
	void monitorLocation()
	{
		try {
			 
			while(!app.canSendLocation2UI && app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING){
    			Thread.sleep(update_interval);
    			printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime );

    		}
			
			
			Location loc =app.playBack?null:app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
			if(loc!=null){
//				lastLocTime =loc.getTime();
				QLog.getLogger().d(dTAG,TAG + " getLastKnownLocation  loc.time " + loc.getTime());
//				  QLog.getLogger().d(dTAG,TAG+" "+ "1, System.currentTimeMillis() - loc.getTime():" 
//						  + String.valueOf(System.currentTimeMillis() - loc.getTime()  ) +",update_interval*5 is "+update_interval*5);
						
			}
//			else
//			{
//				QLog.getLogger().d(dTAG,TAG + " getLastKnownLocation loc is null..");
//			}
//    		if(!app.playBack)loc = app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    		
    		if(loc ==null) loc =app.getLocationCached().size()>0
    				?app.getLocationCached().get(app.getLocationCached().size()-1)
    			    :app.lastLocation;
			if(loc ==null){
				 Log.i(dTAG,TAG + " loc is null..");
			   notifyUI();
//				return;
			}
//			if(loc!=null) QLog.getLogger().d(dTAG,TAG+" "+ "2, System.currentTimeMillis() - loc.getTime():" 
//					  + String.valueOf(System.currentTimeMillis() - loc.getTime()  ) +",update_interval*5 is "+update_interval*5);
			//no location ever get.
//    		while(app.canSendLocation2UI && System.currentTimeMillis() - loc.getTime()<update_interval) {
    	   while(app.canSendLocation2UI && loc ==null && !app.isNetworkLocationRequestStarted){
//    			   &&!app.isNetworkLocationRequestStarted && QiYouConstant.NETWORK_CONNECTED) {
				Thread.sleep(update_interval);
				loc =app.playBack?null:app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        		if(loc ==null) loc =app.getLocationCached().size()>0
        				?app.getLocationCached().get(app.getLocationCached().size())
        			    :app.lastLocation;
				if(loc ==null){
					 Log.i(dTAG,TAG + " loc is null..");
					   notifyUI();
						return;
					}
				printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime );
			 
				
    		}
//    	   if(loc!=null) QLog.getLogger().d(dTAG,TAG+" "+ "3, System.currentTimeMillis() - loc.getTime():" 
//					  + String.valueOf(System.currentTimeMillis() - loc.getTime()  ) +",update_interval*5 is "+update_interval*5); 
    //when ever get one location at least
    	   
//    	   boolean noGps=app.canSendLocation2UI &&  loc!=null && System.currentTimeMillis() - loc.getTime()>update_interval*5
//					&& app.getRecordingTrack().getTrackBean().getStatus()==QiYouConstant.TRACK_STATUS_TRACKING;
//    	   QLog.getLogger().d(dTAG,TAG+" noGps "+noGps);
    	   
//    	   if(loc!=null)   QLog.getLogger().d(dTAG,TAG + "4, getLastKnownLocation  loc.time " + loc.getTime()+", original last time is "+lastLocTime);

    	   while(app.canSendLocation2UI &&  loc!=null && System.currentTimeMillis() -app.lastLocationTime>update_interval*2
					&& app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING &&!app.isNetworkLocationRequestStarted)
			{ 
//					QLog.getLogger().d(dTAG,TAG + "5, getLastKnownLocation  loc.time " + loc.getTime()+", original last time is "+lastLocTime);
//					QLog.getLogger().d(dTAG,TAG+" "+ "5, System.currentTimeMillis() - loc.getTime():" 
//						  + String.valueOf(System.currentTimeMillis() - loc.getTime()  ) +",update_interval*5 is "+update_interval*5); 
//    		   QLog.getLogger().dLog(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis()  " + System.currentTimeMillis()   +",app.lastLocationTime is "+app.lastLocationTime );
//    	 	   QLog.getLogger().dLog(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis() - app.lastLocationTime:" + String.valueOf(System.currentTimeMillis() - app.lastLocationTime  ) +",update_interval*5 is "+update_interval*5);
////				
//    		   QLog.getLogger().d(dTAG,TAG+" "+ " monitorGPS(), System.currentTimeMillis() - loc.getTime():" + String.valueOf(System.currentTimeMillis() - lastLocTime  ) +",update_interval*5 is "+update_interval*5);
//						
					notifyUI();					   
					Thread.sleep(update_interval);
//					printAppStartTime();//QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ app.startTime );
//					monitorLocation();
//				    loc = app.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
//				    lastLocTime =loc!=null?loc.getTime():System.currentTimeMillis();
			 
			}
			
			
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			Utils.logStackTrace(e,TAG);
		}
	  }		
 
	
	
	void notifyUI(){
		 QLog.getLogger().d(dTAG,TAG+" Lost the gps signal...");
		if(app.isNetworkLocationRequestStarted || app.playBack  ) return;
			
			Intent broadcastIntent = new Intent();						
	        broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);  
	        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
	        broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION, new Location(QiYouConstant.LOCATION_MONITOR));
//		    broadcastIntent.putExtra(QiYouConstant.EXTRA_KEY_NO_LOCCATION_SIGNAL, true);    
		    sendBroadcast(broadcastIntent); 
		   
//		    Utils.logStackTrace(new Exception(" Lost the gps signal..."),TAG);
		
	}
	
	void printAppStartTime(){		
		if(app.startTime!=logtime){
			logtime =app.startTime;
		QLog.getLogger().d(dTAG,TAG+" Recording trackid: " +app.getRecordingTrack().getTrackBean().getTrackId() +", app start time: "+ logtime );
		}
	}
	
	@Override
	public void onDestroy() {

//		  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();

	}
	 
}


  
	
 
