package com.qiyou.mb.android.service;

import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log; 

import com.loopj.android.http.JsonHttpResponseHandler;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.content_providers.TrackProvider;
import com.qiyou.mb.android.receivers.TimeTickReceiver;
import com.qiyou.mb.android.ui.Welcome;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;
import com.qiyou.mb.android.utils.server.SharedLocation;

public class LocationService2 extends Service { 
	public static String TAG ="com.qiyou.LocationService2";
	public static final String dTAG ="com.qiyou";
//	public DBserviceNew(String name) {
//		super(name);
//		// TODO Auto-generated constructor stub
//	}


	@Override
	public void onStart(Intent intent, int startId) {
		QLog.getLogger().d(dTAG,TAG+"... service LocationService2 onStart.....," );
		if(intent!=null)
			handleIntent(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		QLog.getLogger().d(dTAG,TAG+"... service LocationService2 onStartCommand.....," );
		handleIntent(intent);
	    // We want this service to continue running until it is explicitly
	    // stopped, so return sticky.
		 return START_STICKY;		
	}
	protected  void handleIntent(Intent intent){
	    	
	    	//to check if the application restart with new instances or not
	    	// The check result is, the new application instance created, the original referenced application still exits.
	    	
	    	//TODO: to find what cause creating new application instances?
	    	
//	    	String debugstring="Time Tick regist at: "+ registTime+ ",  Application instance start time is:" + app.startTime +",Time past:"+( app.startTime -registTime);
//	    	QLog.getLogger().d(dTAG,TAG+ debugstring);
//	    	Utils.logStackTrace(new Exception(debugstring),dTAG);
	    	
	    	
 	    
	if(intent==null)return;
    	 
    	 String key = QiYouConstant.EXTRA_KEY_UPLOAD_SHARED_LOCATION;  
    	if (intent.hasExtra(key)){
    		
    		sendSharedLocation();
//    		postJsonWS()
    		
     		return;
    	}
	    }
 

 	protected QiYouApplication app;
	

	 @Override
	  public void onCreate() {
	    super.onCreate();
	    app =(QiYouApplication)this.getApplication();
  	  }
 
	 
	 
	 void sendSharedLocation(){
		 
		 if(app.lastLocation ==null){
			 return;
		 }
		 
		 
		 SharedLocation sl = new SharedLocation();
		 sl.setBear(app.lastLocation.getBearing());
		 sl.setLat(app.lastLocation.getLatitude());
		 sl.setLon(app.lastLocation.getLongitude());
		 sl.setSpeed(app.lastLocation.getSpeed());
		 sl.setEle((float) (app.lastLocation.getAltitude()));
//		 sl.setTime(app.lastLocation.getTime()); //to use server time
		 sl.setId(app.user.getUserbean().getId());
		 sl.setName(app.user.getUserbean().getUserName()/*.getAccount()*/);
		 sl.setExpired( QiYouConstant.PV_INT_LIVE_TERM);
		 sl.setDist((float) app.sumDist);
		 sl.setType(0);
		 sl.setFace(0);
		 sl.setMsg(QiYouConstant.PV_STR_SHARE_MSG);
		 
		 
    	 QLog.getLogger().d(dTAG, TAG+" begin to post shared location.............."); 

		 postJsonWS(Utils.getGsonString(sl),RestMethods.LIVE_P_SHARE_LOCATION);
		 
		 
		 
		 
		 
	 }
	 
	 
	 int failureCnt=0;
	 
	 void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{
		 failureCnt =0;
//		 if(jsonObject==null)return;
		 
		 if(method.equalsIgnoreCase(RestMethods.LIVE_P_SHARE_LOCATION)){
			 app.lastSharedTime=System.currentTimeMillis();
			 QLog.getLogger().d(dTAG, TAG+" shared success!  app.lastSharedTime  " + app.lastSharedTime); 
		 } 
		
	 }
	
	 void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){
		 QLog.getLogger().d(dTAG, TAG+" shared failure!"); 
		 failureCnt++;
		 if(failureCnt<=3){
			 QLog.getLogger().d(dTAG, TAG+" shared failure,tring count 1....."); 
			 sendSharedLocation();
		 }
	 }
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 void postJsonWS(String json,String url) {
    	 if(!Utils.isNetworkConnected(this)){			 
			 return;
		 }   
//    	 setCookie();
  
    	 QLog.getLogger().d(dTAG, TAG+" post json is "+json); 
		// Show Progress Dialog
	 
	   
		// Make RESTful webservice call using AsyncHttpClient object
//		testCookies();
		 StringEntity entity =null;
		try {
			entity = new StringEntity(json,HTTP.UTF_8);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		if(entity==null)return;
		
		entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		
//		QiyouRestClient.post(activity,url, entity,"application/json",
		QiYouApplication.post( app,url, entity,"application/json",
				new JsonHttpResponseHandler(){ 
					@Override
					public void onSuccess(int statusCode, org.apache.http.Header[] headers,   JSONObject response){
					 
						 if (response != null) { 
							 try {
//								 JSONObject jsonObject=	 response.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ;
								 JSONObject jsonObject=	null;  
									try { 
									      jsonObject=	response.getJSONObject(QiYouConstant.JSONOBJECT_KEY);
										 
									} catch (JSONException e) { 
									 
									}
								 String method =response.has(QiYouConstant.SIGN_KEY)?response.getString(QiYouConstant.SIGN_KEY):"";
								 String msg=response.getString(QiYouConstant.MSG_KEY);
								processJsonObject(method,  jsonObject,msg);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								Utils.logStackTrace(e, dTAG);
							}
							 
						 }
					}
					
					 
					
				        String msg = "";
					 /**
					     * Returns when request failed
					     *
					     * @param statusCode    http response status line
					     * @param headers       response headers if any
					     * @param throwable     throwable describing the way request failed
					     * @param errorResponse parsed response if any
					     */
					    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
					        // QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], Throwable, JSONObject) was received");
					       
							try {
//								 JSONObject jsonObject=	 errorResponse.getJSONObject(QiYouConstant.JSONOBJECT_KEY) ;
//								 String method =jsonObject.has(QiYouConstant.SIGN_KEY)?jsonObject.getString(QiYouConstant.SIGN_KEY):"";
//								 String msg=errorResponse.getString(QiYouConstant.MSG_KEY);
								msg = errorResponse==null?null:errorResponse.getString(QiYouConstant.MSG_KEY);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								Utils.logStackTrace(e, dTAG);
							}
					        asynClientOnFailure(statusCode,msg,headers);
					    }

					    /**
					     * Returns when request failed
					     *
					     * @param statusCode    http response status line
					     * @param headers       response headers if any
					     * @param throwable     throwable describing the way request failed
					     * @param errorResponse parsed response if any
					     */
					    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
					    	 // QLog.getLogger().d(dTAG, TAG+", onFailure(int, Header[], Throwable, JSONArray) was received" );
					    	 asynClientOnFailure(statusCode,msg,headers);
					    }

					    

					@Override
					public void onFailure(int statusCode, org.apache.http.Header[] headers,  String errorResponse, java.lang.Throwable throwable  ) {
						QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], String, Throwable)  was received" );
						QLog.getLogger().d(dTAG,  TAG+"errorResponse: "+errorResponse);
						asynClientOnFailure(statusCode,msg,headers);
					}
					@Override
					public void onProgress(int bytesWritten, int totalSize) {
 
					}
				});
		 
		
	}
	 
	 
	
	 
	 
	 @Override
	public void onDestroy() { 
	       super.onDestroy(); 
	 }

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
