package com.qiyou.mb.android.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

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 com.google.gson.JsonSyntaxException;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.Statistics;
import com.qiyou.mb.android.beans.basic.GPItem;
import com.qiyou.mb.android.beans.basic.Statics_bean;
import com.qiyou.mb.android.utils.FileUtil;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

public class sync extends Service {
	public final static String TAG="com.qiyou.sync";
	public static final String dTAG ="com.qiyou";
	protected QiYouApplication app;
	
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
	    // TODO Auto-generated method stub
	    super.onCreate();
	    // QLog.getLogger().d(dTAG,TAG+"... service sync onCreate.....," );
		if(app==null)
			app =(QiYouApplication)this.getApplication();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		QLog.getLogger().d(dTAG,TAG+"... service sync onStart.....," );
		if(app==null)
			app =(QiYouApplication)this.getApplication();
		if(intent!=null)
			handleIntent(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		QLog.getLogger().d(dTAG,TAG+"... service sync 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){
	    	
 
	    	if(intent==null)return;
	    	
	    	  String key =  QiYouConstant.ACTION_SYNC_STATISTICS ;  

		         if (intent.hasExtra(key)) { 
//		        	 QLog.getLogger().d(dTAG, TAG+(app.isStaticsticsDone?" it is ready for sync....   ":" it has been in sycing, return...   "));
		        	
//		        	 return;
		        	 
		        		int exit =Integer.valueOf(intent.getExtras().get(key).toString());
		        		isExitApp = exit ==1;
		        		
		        		 if(app.isStaticsticsDone || isExitApp){
			        		 app.isStaticsticsDone=false;
			        		 checkStatiscsStatus(); //同步statistic
			        	 }
		         }
	    }
	
	int userId;
	boolean isExitApp = false;
//	boolean isStaticsticsDone=false;
    void checkStatiscsStatus(){
//    	QLog.getLogger().d(dTAG, TAG+" begin do the statistics sync..................");
    	 int topWaiting=0;
    	 if   (app.mStatistics==null ||	app.statTrackLoading){
    		 app.isStaticsticsDone=true;
    		 return;
    	 }
    	 while(app.mStatistics==null ||	app.statTrackLoading)
	   	     try {
	   			Thread.sleep(100); 
//	   			app.getBdGEOadress(lat,lon);
	   			topWaiting+=100;
 	   		     QLog.getLogger().d(dTAG,TAG+" statistics 初始化中。。。"+topWaiting);
	   			if(topWaiting>QiYouConstant.MAX_TIME_GET_TRACK_FROM_DB*5) { 
	   				break; 

	   			}
	   		  } catch (InterruptedException e) {
	   			// TODO Auto-generated catch block
	   			Utils.logStackTrace(e, TAG);
	   		 } 
   
//    	   QLog.getLogger().d(dTAG,TAG+" statistics  is:" + Utils.getGsonString(app.mStatistics));
    	   
    	   
    	 userId=app.user.getUserbean().getId(); 
    	 
    	 if(userId<=0 && !QiYouConstant.DEVELOPER_MODE){ //only sync known user.
    		 app.isStaticsticsDone=true;
    		 return;
    	 }
    
    	  userId=userId>0?userId:app.getPhoneId();	 
    	  
     	  QLog.getLogger().dLog(dTAG,TAG+" statitics identify id is "+userId);
    	  
    	 
    	 if(app.mStatistics==null ||userId ==-1){
    		 
    		 exitService();
    		 return;
    	 }
    	
    	 QLog.getLogger().dLog(dTAG, TAG+" check timestamp, need to check with web? " + (app.mStatistics.getLastTime()==app.getLastStatSyncTime()) );
    	 if(app.getLastStatSyncTime()>0 && app.mStatistics.getLastTime()==app.getLastStatSyncTime()){
     		
    		 if (!QiYouConstant.DEVELOPER_MODE){
    			 QLog.getLogger().d(dTAG,TAG+" 。。。。。。。。。。。。。。。。。。。。。没有更新需要同步");
    			 exitService();
    			 return;
    		 }
      		 
    	 }
        
		  RequestParams params = new RequestParams();  
			 params.add("userid", String.valueOf(userId));
			 params.add("from", String.valueOf(app.mStatistics.getFirstTime()));
			 params.add("to", String.valueOf(app.mStatistics.getLastTime())); 
			 params.add("dist", String.valueOf((int)app.mStatistics.getSumDist())); 
          QLog.getLogger().d(dTAG, TAG+" begin to check web statistics........., web query params: "+params);
		  getJsonWs(params,  RestMethods.USER_G_USER_STAT_STATUS/*"mb/user/statistics/status"*/); 
	        
         
	}
    
    
    
    
	
	boolean isPostStatics;  
    String lastStatName=QiYouConstant.STAT_TEXT+"_last"	  ;
    Statistics deltaStatistics=null;
    
    void postStatiscs(){
		 
		  if(isPostStatics)return;
		  
		  isPostStatics=false;
		  
		Statistics mLastStatistics=null;
		
		 StringBuffer statJson=new StringBuffer(); 
		 
		String deltaName=QiYouConstant.STAT_TEXT;
			  try {
				  lastStatName=QiYouConstant.STAT_TEXT+"_last"+userId; //use the phoneid/userid as last synced name.
//				   QLog.getLogger().d(dTAG, TAG+" begin to read last Statistics from "+ lastStatName +"  ..........................................." );
				  
//	 			    FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_en", QiYouConstant.STAT_TEXT, crypto, entity);   
//					statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT));
					statJson.append(FileUtil.readEncodedFile(lastStatName, app.crypto, app.entity));
//					 QLog.getLogger().d(dTAG, " QiYouConstant.STAT_TEXT is: "+QiYouConstant.STAT_TEXT );
					 QLog.getLogger().dLog(dTAG, TAG+" last statJsn is: "+statJson.toString() );
					  
//	 			  	Utils.writeSDFile(lastStatName +"_de", statJson.toString());  
//				  	Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); 
				  	
	 			  	mLastStatistics= (Statistics)Utils.getGsonObject(statJson.toString(), Statistics.class) ;
			        
//			        QLog.getLogger().d(dTAG, " read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ........................................... done" );
				 
				 }catch( JsonSyntaxException je){
					 Utils.logStackTrace(je, TAG);
					 mLastStatistics=null;
	 			}/*  catch (IOException e) {
//					// TODO Auto-generated catch block
	 				e.printStackTrace();
				}  */				   
//			  mLastStatistics =mLastStatistics==null?new Statistics():mLastStatistics;
			  statJson=new StringBuffer(); 
			  
			  try {
				   QLog.getLogger().d(dTAG, TAG+" begin to read delta Statistics from "+ deltaName +"  ..........................................." );
				  
//	 			    FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_en", QiYouConstant.STAT_TEXT, crypto, entity);   
//					statJson.append(Utils.readSDFile(QiYouConstant.STAT_TEXT));
					statJson.append(FileUtil.readEncodedFile(deltaName, app.crypto, app.entity));
//					 QLog.getLogger().d(dTAG, " QiYouConstant.STAT_TEXT is: "+QiYouConstant.STAT_TEXT );
					 QLog.getLogger().dLog(dTAG, TAG+" delta statJsn is: "+statJson.toString() );
					  
//	 			  	Utils.writeSDFile(deltaName +"delta_de", statJson.toString());  
//				  	Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); 
				  	
	 			  	deltaStatistics= (Statistics)Utils.getGsonObject(statJson.toString(), Statistics.class) ;
			        
//			        QLog.getLogger().d(dTAG, " read Statistics from "+ QiYouConstant.STAT_TEXT+"_en ........................................... done" );
				 
				 }catch( JsonSyntaxException je){
					 Utils.logStackTrace(je, TAG);
					 deltaStatistics=null;
					 this.exitService();
	 			} /* catch (IOException e) {
//					// TODO Auto-generated catch block
	 				e.printStackTrace();
				}  		*/		   
			  
			  QLog.getLogger().dLog(dTAG, TAG+" lastStaitistics is null? "+(mLastStatistics==null) );
			  
			 /* HashMap<String,GPItem> deltaList=new HashMap<String,GPItem>();	
			  HashMap<String,GPItem> lastList=new HashMap<String,GPItem>();	
			  if(deltaStatistics!=null && deltaStatistics.getGpList().size()>100){  //remove duplicated ones
				  int ikey=0;
				  GPItem item;
				  for(Integer key:deltaStatistics.getGpList().keySet()){
					  item =deltaStatistics.getGpList().get(key);
					  if(item!=null){
						  deltaList.put(item.getLat()+"_"+item.getLng(), item);
					  }
				  }
				   
				  deltaStatistics.getGpList().clear();
				  for(String key:deltaList.keySet()){
					  item =deltaList.get(key);
					  if(item!=null){
						  deltaStatistics.getGpList().put(ikey, item);
						  ikey++;
					  }
				  }
				  
				  
				  
				  if(mLastStatistics!=null){
					  for(Integer key:mLastStatistics.getGpList().keySet()){
						  item =mLastStatistics.getGpList().get(key);
						  if(item!=null){
							  lastList.put(item.getLat()+"_"+item.getLng(), item);
						  }
					  }
					  
					  ikey=0;
					  mLastStatistics.getGpList().clear();
					  for(String key:lastList.keySet()){
						  item =lastList.get(key);
						  if(item!=null){
							  mLastStatistics.getGpList().put(ikey, item);
							  ikey++;
						  }
					  } 
				  }
				  
			  }*/
			  
			  if(mLastStatistics!=null && deltaStatistics!=null){
				   QLog.getLogger().d(dTAG, TAG+" begin to build data for sync..........................................." );

//				  ConcurrentHashMap<Integer,TypeStatistics>  StatisticsTracks =new ConcurrentHashMap<Integer,TypeStatistics>();
				  // to get delta sbs				   
				  for(Integer key:deltaStatistics.getStatisticsTracks().keySet()){

					  QLog.getLogger().dLog(dTAG, TAG+ String.format(" checking track type, GPX type value is %s, current type value %s ", TrackType.GPX.toInt(), key.intValue()) );

					  if (key.intValue()==TrackType.GPX.toInt()){ // will equal?
						  deltaStatistics.getStatisticsTracks().remove(key); 
						  continue;						  
					  }
					  if(mLastStatistics.getStatisticsTracks().keySet().contains(key)){
						  if(deltaStatistics.getStatisticsTracks().get(key).getEnd()>0 &&
								  deltaStatistics.getStatisticsTracks().get(key).getEnd()
								  > mLastStatistics.getStatisticsTracks().get(key).getEnd()){
							  Statics_bean sb=null;
							   
							  for(Integer trackId: deltaStatistics.getStatisticsTracks().get(key).getSbs().keySet()){
								  sb =deltaStatistics.getStatisticsTracks().get(key).getSbs().get(trackId);
								  if(sb!=null && sb.getStartTime()<=mLastStatistics.getStatisticsTracks().get(key).getEnd()){
									  deltaStatistics.getStatisticsTracks().get(key).getSbs().remove(trackId);
									  QLog.getLogger().dLog(dTAG, TAG+" deltaStatistics removed " +trackId );
								  }
							  }
						  }
						 
					  }
				  }
				 
				  
				  //to get delta gp
				  HashMap<Integer,GPItem> gpList=new HashMap<Integer,GPItem>();		 
				 
			   /*	
			    * 	NOT TO UPLOAD FOOTMARKS TO SERVER 2016.01.06
			    *   
			    *   
			    *   QLog.getLogger().dLog(dTAG, TAG+ String.format(" 1 delta gp size %s,last stat gp size %s",deltaStatistics.getGpList().size(),mLastStatistics.getGpList().size()) );
			    */
				  int ikey=0;
				  if(deltaStatistics.getGpList().size() > mLastStatistics.getGpList().size()){
					  QLog.getLogger().dLog(dTAG, TAG+ String.format(" 2 delta gp size %s,last stat gp size %s",deltaStatistics.getGpList().size(),mLastStatistics.getGpList().size()) );
					 for(Integer key:deltaStatistics.getGpList().keySet()){
						 if(!mLastStatistics.getGpList().containsValue(deltaStatistics.getGpList().get(key))){
								gpList.put(ikey, deltaStatistics.getGpList().get(key));							
								 QLog.getLogger().dLog(dTAG, TAG+String.format(" key is %s,new key is %s,put in gp %s " ,key,ikey, Utils.getGsonString(deltaStatistics.getGpList().get(key))) );
								 ikey++;
								 if(ikey>100){ //limit to 100 for each sync
									 break;
								 }
						 }
					 } 
				  }
				   
				  deltaStatistics.setGpList(gpList);
				  
			  }
			  
			  
			  
			  deltaStatistics.setUserId(userId);
			  isPostStatics=true;
			  this.postJsonWS(Utils.getGsonString(deltaStatistics) , RestMethods.USER_P_USER_STAT/* "mb/user/statistics"*/);  
			  
			 QLog.getLogger().dLog(dTAG, TAG+" post delta statistics jason is " +  Utils.getGsonString(deltaStatistics) );
			  
			   
	}
	
     void getStatiscs(){
//    	 int userId=app.user.getUserbean().getId(); 
//    	 if(userId<=0)return;
    	 
    	 RequestParams params = new RequestParams();  
		params.add("userid", String.valueOf(userId)); 
		QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
        getJsonWs(params, RestMethods.USER_G_USER_STAT/*"mb/user/statistics"*/);
     
        
	}
    
 
	 
	
     void writeLastStatistics(){
    	 try { 
    		 app.setLastStatSyncTime(app.mStatistics.getLastTime());
    		 QLog.getLogger().d(dTAG,TAG +" last sync stat time is " + app.mStatistics.getLastTime());
		     Utils.writeSDFile(lastStatName+"_tmp",Utils.getGsonString(app.mStatistics)); 
 		     FileUtil.encodeFile(lastStatName, lastStatName+"_tmp", app.crypto, app.entity);
			 
//			 FileUtil.decodeFile(QiYouConstant.STAT_TEXT+"_conseal_en", QiYouConstant.STAT_TEXT+"_conseal_plain", crypto, entity);
			 
		    
//		     FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_conseal",  gson.toJson(mStatistics) ); 
//		     FileUtil.writeFile(this.crypto,this.entity, QiYouConstant.STAT_TEXT+"_test", "a" );
//		     Utils.writeSDFile( QiYouConstant.STAT_TEXT+"_test_a","a" );		
//		     Utils.writeSDFile(QiYouConstant.STAT_TEXT+"_test_a_dd",FileUtil.readFile(QiYouConstant.STAT_TEXT+"_test", crypto, entity)); 
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e, TAG); 
			/*} catch (CryptoInitializationException e) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e, TAG); 
			} catch (KeyChainException e) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e, TAG);
				 */
			}
     }
     
     
	 void processJsonObject(JSONObject jsonObject)throws JSONException{
		 if(isPostStatics){
			 isPostStatics=false;
		     QLog.getLogger().d(dTAG,TAG +" statistics 上传成功 ");
		    
		     
		     
		     
		     writeLastStatistics();
//			 app.isStaticsticsDone=true;
		     exitService();
			 QLog.getLogger().d(dTAG,TAG+ " statistics 同步结束");
		 }
	  }
	
	void processWebStatistics(JSONObject jsonObject){ 
		  
			 try {
				 
				 String msg =jsonObject.getString(QiYouConstant.MSG_KEY);
				
				 if( !TextUtils.isEmpty(msg) && !msg.equalsIgnoreCase("null")){ //检验当前手机端的statistics相对server端的时间戳
					
					 boolean toGet = false;
					 boolean toPost = false;
					 
					 int i =-1;
					 try{
						 i =Integer.valueOf(msg);
						 toGet =i==0;
						 toPost=i==1;
						 
						 
					 }catch(NumberFormatException e){
						  
					 }
					 
					 
					   QLog.getLogger().d(dTAG,TAG+" returnned statistics status is "+msg);
					   QLog.getLogger().d(dTAG,TAG+" "+(toGet?"begin to get statistics from web....":toPost?" begin to post statistics to web....":" nothing need to do, return..."));
					
					/*if(jo.has("get")){
						toGet =jo.getBoolean("get");  
					}
					if(jo.has("post")){
						toPost  = jo.getBoolean("post");							
					}*/
					  
					   
					   if ( QiYouConstant.DEVELOPER_MODE){
//						   toGet = true;
//						  toPost = true;
					   }
					   if(toGet){
						getStatiscs();
					}else if(toPost){
						postStatiscs();
					}else{
						exitService();
					}
					
					 return;
				 }
				 
				 
				 
				 //取到服务端的statistic，更新本地的statiscs 
				 QLog.getLogger().d(dTAG,TAG+" to store statistics........ ");
				 JSONObject jo =jsonObject.getJSONObject(QiYouConstant.JSONOBJECT_KEY);
				 
				 if(jo==null){
//					 app.isStaticsticsDone=true;
					 QLog.getLogger().d(dTAG,TAG+" statistics 同步结束");
					 exitService();
					 return;
				 }
					 
				 app.mStatistics = (Statistics)Utils.getGsonObject(jo.toString(), Statistics.class);
				 app.getStaticsTracks();  //合并本地数据库数据并保存 
//				 checkStatiscsStatus();  //do sync with new statistics
//				 app.isStaticsticsDone=true;
				 writeLastStatistics(); //write last stat.
				
				 
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Utils.logStackTrace(e, dTAG); 
					 
				}catch(Exception e){
					Utils.logStackTrace(e, dTAG); 
				 
				}
			
			 QLog.getLogger().d(dTAG,TAG+" statistics 同步结束");
		     exitService();
			 
		
	}
	
	
	
     void postJsonWS(String json,String url) { 
    	   
	 
		 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){
//						isPostStatics=false;
						 if (response != null) { 
							 try {
//								processJsonObject(  response.getJSONObject(QiYouConstant.JSONOBJECT_KEY));
								 processJsonObject( null);
							} 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");
					        isPostStatics=false;
							try {
								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) {
					    	isPostStatics=false;
					    	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  ) {
						isPostStatics=false;
						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) {
						// TODO Auto-generated method stub
						super.onProgress(bytesWritten, totalSize);
						int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
						// 上传进度显示
					 
						QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize);
					}
				});
		 
	}
     
     void getJsonWs(RequestParams params,String url){
		 
		 
		 QiYouApplication.get(url, params, new JsonHttpResponseHandler() {
	            @Override
	            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
	            	 
	            	QLog.getLogger().d(dTAG,  TAG+", onSuccess(int statusCode, Header[] headers, JSONObject response) was received");
				 
				   processWebStatistics(  response);
						 
						 
//					 }
	            }
	            
	          
	            String msg = "";
	            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
			        QLog.getLogger().d(dTAG,  TAG+", onFailure(int, Header[], Throwable, JSONObject) was received");
			       
					try {
						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);
			    }
	            
	        	@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) {
					// TODO Auto-generated method stub
					super.onProgress(bytesWritten, totalSize);
					int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
					// 上传进度显示
				 
					QLog.getLogger().d(dTAG,"上传 Progress>>>>>"+ bytesWritten + " / " + totalSize);
				}
					
	        });
		   
	 }
     
     
     void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){
			// Response failed :(
			 
			if(headers!=null)
			 for (Header h : headers) {
				 QLog.getLogger().d(dTAG,  TAG+"    "+ h.getName() + " " + " " + h.getValue() + "");
			    }
			
			 QLog.getLogger().d(dTAG,  TAG+"   failure msg: "+ msg);
			 QLog.getLogger().d(dTAG,  TAG+"   failure statusCode: "+ statusCode); 
			// Hide Progress Dialog
			 
			// When Http response code is '404'
			if (statusCode == 404) {
//				Toast.makeText(activity,
//						"Requested resource not found" +msg,
//						Toast.LENGTH_LONG).show();
				 
			}
			// When Http response code is '500'
			else if (statusCode == 500) {
//				Toast.makeText(activity,
//						"Something went wrong at server end" +msg,
//						Toast.LENGTH_LONG).show();
				 
			}
			// When Http response code is '500'
			else if (statusCode == 417) {
				 
			}
			// When Http response code other than 404, 500
			else {
//				Toast.makeText(
//						activity,
//						"Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]" +msg,
//						Toast.LENGTH_LONG).show();
				 
			}
			exitService();
		}
     
     void exitService(){
    	 app.isStaticsticsDone=true;
    	 app.isNewLogin=false;
    	 this.stopSelf();
     }
	
     @Override
 	public void onDestroy() { 
    	 QLog.getLogger().d(dTAG, TAG+" going to destory");
 	       super.onDestroy(); 
 	       if (isExitApp){
// 	    	  this.getApplicationContext()
// 	    	   System.exit(0);
 	       }
 	       
 	 }
	
}
