package com.qiyou.mb.android.service;

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

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
//import com.baidu.location.BDLocation;
//import com.baidu.location.BDLocationListener;
//import com.baidu.location.LocationClient;
//import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.basic.GEOaddress;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;

public class BDLocationSvc extends IntentService {

	public final static String TAG = "com.qiyou.BDLocationSvc";
	public final static  String dTAG = "com.qiyou";
	
	LocationClient mLocClient;
    MyLocationListenner myListener ;
    QiYouApplication app ;
	public BDLocationSvc() {
		super(TAG);
		// TODO Auto-generated constructor stub
	}

	public BDLocationSvc(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate() {
//		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);		
		super.onCreate();
		if(!QiYouConstant.NETWORK_CONNECTED  ){  
//		if(!Utils.isNetworkConnected(getApplicationContext())){
			
			app.isNetworkLocationRequestStarted=false;
			this.stopSelf();
		}
		app = (QiYouApplication) this.getApplication();
		if(app.mLocClient==null){
			app.mLocClient = new LocationClient(getApplicationContext());
		}
		mLocClient =app.mLocClient;
		if(app.bdListener==null){
			app.bdListener = new MyLocationListenner();
		}
		
		myListener = (MyLocationListenner) app.bdListener;
		
		QLog.getLogger().d(dTAG, TAG +" Begin to request BDlocation service...");
		
	}
//	boolean isOffMap;
//	boolean isLocation;
	
	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		
		if(app.isNetworkLocationRequestStarted) return;
		app.isNetworkLocationRequestStarted=true;
//		isOffMap=false;
//		isLocation=false;
		String key;
//		Bundle extras = intent.getExtras();
		String value=null;
		key =QiYouConstant.EXTRA_KEY_NETWORK_LOCATION;
		if(intent.hasExtra(key)){
			value=	intent.getExtras().getString(key);
			QLog.getLogger().d(dTAG, TAG+ " get extra vlaue of: "+value);
		}
		if(TextUtils.isEmpty(value)) return;
		QiYouConstant.NETWORK_LOCATION_FOR_GEO =value.equalsIgnoreCase(QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY);
		QiYouConstant.NETWORK_LOCATION_FOR_LOCATION=value.equalsIgnoreCase( LocationManager.KEY_LOCATION_CHANGED);;		
//		key = QiYouConstant.EXTRA_KEY_GET_CURRENT_CITY;
// 		isOffMap =intent.hasExtra(key);
// 		
//		key = LocationManager.KEY_LOCATION_CHANGED;
//		isLocation=intent.hasExtra(key);
		
		startRequestLocation() ;
	}
	 class MyLocationListenner implements BDLocationListener {
			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub
				if (location == null)
					return;
		//		 if (location.getLocType() == BDLocation.TypeGpsLocation) 
			    int errCode=location.getLocType();
				QLog.getLogger().d(dTAG, TAG +" BDlocation error code:" + location.getLocType());
				if(errCode==161){
					if(QiYouConstant.NETWORK_LOCATION_FOR_LOCATION && app.canSendLocation2UI){
						app.isNetworkLocationRequestStarted =true;
						QLog.getLogger().d(dTAG, TAG +" get locaiton info for network location service....");

						QLog.getLogger().d(dTAG, TAG +" option.getScanSpan: "+ mLocClient.getLocOption().getScanSpan());
//						if(app.playBack ||!app.canRecord()&&!app.isRouting){
						if(app.canStopNetworkRequest()){
							stopRequestLocation();
							return;
						}
							
						Location loc =new Location(QiYouConstant.LOCATION_BD_LOC);
						loc.setLatitude(location.getLatitude());
						loc.setLongitude(location.getLongitude());
						loc.setAccuracy(location.getRadius()); 
					 
						Intent broadcastIntent = new Intent();
						broadcastIntent.setAction(QiYouConstant.ACTION_NEW_LOCATION_GETBACK);
						broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);							 
						broadcastIntent.putExtra(QiYouConstant.NEW_LOCATION,loc);
						broadcastIntent.putExtra(QiYouConstant.ACTION_NEW_COARSE_LOCATION,"");
						
						sendBroadcast(broadcastIntent); 
						
					} else				
					if(QiYouConstant.NETWORK_LOCATION_FOR_GEO){
						QLog.getLogger().d(dTAG, TAG +" offmap update...get locaiton info for offmap..."); 
					
					
						if(app.getGEOinfo()==null || 
								app.getGEOinfo()!=null && !app.getGEOinfo().getDistrict().equalsIgnoreCase(location.getDistrict())){
							GEOaddress go =new GEOaddress(); 
							go.setCity(location.getCity());
							go.setCityId( location.getCityCode());
							go.setProvince(location.getProvince());
							go.setStreet(location.getStreet());
							go.setStreetNo(location.getStreetNumber());
							go.setDistrict(location.getDistrict());
							go.setLat((float) location.getLatitude());
							go.setLon((float) location.getLongitude());
							QLog.getLogger().d(dTAG, TAG +String.format(" offmap update...BDLocation get cityId :%s,cityName :%s",location.getCityCode(),location.getCity()));
					        app.setGEOinfo(go); 
					        
					   	 	 int networkType =Utils.getNetworkType(app);
					   	 	 if(networkType==-1) return; //no active network 
							 if( networkType == QiYouConstant.NETWORK_TYPE_WIFII && app.canUpdateOffmap()){  
								   
								 QLog.getLogger().d(dTAG, TAG +" offmap update...begin to check offmap status..."); 
//								app.setlastOffMapRequestTime();
								
									Gson gson = new Gson();	
				 					String jsonGo=null;	
									try{
											jsonGo = gson.toJson(go);
										}catch(Exception e)
										{
											Log.e(TAG,jsonGo);
											Utils.logStackTrace(e, dTAG);
										} 
									 QLog.getLogger().d(dTAG, TAG +" offmap update...jsonGo is..." +jsonGo); 
									Intent intent = new Intent();						
									intent.setAction(QiYouConstant.ACTION_NEW_COARSE_LOCATION);				
									intent.putExtra(QiYouConstant.EXTRA_KEY_OFFMAP, jsonGo);	
									sendBroadcast(intent);
							 }  
							 
						}
					    	stopRequestLocation(); //for offmap, request once only to get cityId
					}  			
					
				} 
				
				if( !QiYouConstant.NETWORK_CONNECTED || !(QiYouConstant.NETWORK_LOCATION_FOR_LOCATION && app.canSendLocation2UI))
					stopRequestLocation(); 
			}
		
			 
 
		}
	 
	    void setLocationOption() { 
			LocationClientOption option = new LocationClientOption();
			 
//			option.setOpenGps(true); // 打开gps
			option.setAddrType("all");
			option.setCoorType("bd09ll"); // 设置坐标类型
//			option.setServiceName("com.baidu.location.service_v2.9"); // ? 
			option.setScanSpan(5000); // 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
			//option.disableCache(true);
			option.setPriority(LocationClientOption.GpsFirst);
//			option.setPoiNumber(1);
			mLocClient.setLocOption(option); // 2.x版本以后的定位给API支持在API运行过程中，热切换配置参数。
			
		}
	 
		  void startRequestLocation() {
//			  stopRequestLocation();
			// this nullpoint check is necessary
			if (mLocClient != null) {
				setLocationOption();
				mLocClient.registerLocationListener(myListener); 
				mLocClient.start();
				mLocClient.requestLocation();
				QLog.getLogger().d(dTAG, TAG +" mLocClient start Request Location. ");
//				startTime = System.currentTimeMillis();
//				app.isNetworkLocationRequestStarted=true;
			}
		}

		  void stopRequestLocation() {
			if (mLocClient != null) {
				mLocClient.unRegisterLocationListener(myListener);
				mLocClient.stop();
				app.isNetworkLocationRequestStarted=false;
				QLog.getLogger().d(dTAG, TAG +" mLocClient stop Request Location. ");
			}
		}
		  @Override
		  public void onDestroy() {

//			    Log.i(dTAG,  TAG +" Services onDestory");
//			    stopRequestLocation() ;
				// // 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();

			}

}
