package com.qiyou.mb.android.service;

import java.util.ArrayList;

import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.util.Log;
//import com.baidu.mapapi.map.MKOLSearchRecord;
//import com.baidu.mapapi.map.MKOLUpdateElement;
//import com.baidu.mapapi.map.MKOfflineMap;
//import com.baidu.mapapi.map.MKOfflineMapListener;
//import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
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 OfflineMapService extends IntentService {  
//	public class OfflineMapService extends IntentService implements MKOfflineMapListener {
	public static String TAG ="com.qiyou.OfflineMapService"; 
	public static String dTAG ="com.qiyou"; 
	
//	private MapView mMapView = null;
	private MKOfflineMap mOffline = null;  
//	private MapController mMapController = null;
	protected QiYouApplication app;
	int ratio=0;
	private ArrayList<MKOLUpdateElement>localMapList =null;
	int tryTimes=0;
	public OfflineMapService()
	{
	 super(TAG);
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		app = (QiYouApplication) this.getApplication(); 
		initialOffMap();
	}

	
	public OfflineMapService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}
	String cityName;
	@Override
	protected void onHandleIntent(Intent intent) {
		
		
		QLog.getLogger().d(dTAG, TAG+ " offmap update...Network location OfflineMap service get intent...");
//		if(mMapView==null) return;
		 importFromSDCard(); //scan the latest baiduSDK path
		
//		if(app.isOfflimeMapWorking) return;
//		
//		if(!app.isNetworkLocationRequestStarted) {
//			app.startNetworkLocationRequest();
//			return;
//		}
//		app.isOfflimeMapWorking =true;
		 
	/*		 
		String key;
	Location loc=null;
		Bundle extras = intent.getExtras();
		if(extras!=null){
			key =  LocationManager.KEY_LOCATION_CHANGED; 
			loc = (Location) extras.get(key);
		}
		if(loc==null) loc = app.lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if(loc!=null)
		{
			app.stopNetworkLocationRequest();
			String cityName =getCityName(loc);
//			 cityName ="苏州";
			int cityId =search(cityName );
			
//		    if(cityId>0 &&  needDownload(cityId)) 
//		       downloadCityMap(cityId);  
			DownloadOffmap(cityId); 
			     
			
		}*/
	     int cityId =-1;
	     String key  = QiYouConstant.EXTRA_KEY_OFFMAP;		
		 String Gstring = intent.getExtras().getString(key);
		 if(Gstring!=null){
				Gson gson = new Gson();	
				GEOaddress go=null ;
				try{ 
				    go = gson.fromJson(Gstring, GEOaddress.class);  
				
				}catch(Exception e)
				{
					Log.e(dTAG,TAG+" fromJson error: "+Gstring); 
			        Utils.logStackTrace(e, dTAG);
					 
				}
				
			  if(go!=null && go.getCityId()!=null){
				      cityId  =Integer.valueOf( go.getCityId());
				      cityName=go.getCity();
				  	  QLog.getLogger().d(dTAG,   String.format(" offmap update... %s trying check the current city offline map: %s",TAG,cityName)); 
			  } 
				
		 } 
		
	   DownloadOffmap(cityId);  
	   
	   app.setlastOffMapRequestTime();
	}
	
	
	void  DownloadOffmap(int cityId){
//		MKOLUpdateElement e
			boolean rt = true;	
		if(localMapList ==null){
			QLog.getLogger().d(dTAG, TAG+" No offlineMap  downloaded before."); 
		}else  
        for(MKOLUpdateElement e: localMapList){
        	 
        	if(e.update){
        		ratio =0; 
//        		mOffline.remove(cityId);
        		downloadCityMap(e.cityID,e.cityName);
        	} 
        	
//        	}else if(e.update || e.ratio<100) {
            else if(e.ratio<100) {  
        		ratio =e.ratio;  
        		tryTimes =0; //initilize the trytimes for the cityid
        		downloadCityMap(e.cityID,e.cityName);
        	}
        	
        	       	 
        	if(e.cityID == cityId ){
        		rt = false;
        	}
        		/*QLog.getLogger().d(dTAG, TAG+ String.format("发现历史下载%s，上次下载 %d",e.cityName,e.ratio) );        		
//        		rt = e.update || e.ratio<100;
        		rt = e.ratio<100;
        		if(e.ratio<100){
        			ratio =e.ratio;
        			QLog.getLogger().d(dTAG, TAG+ String.format("发现未下载完成地图%s，上次下载 %d",e.cityName,e.ratio) );
        			tryTimes =0; //initilize the trytimes for the cityid
            		downloadCityMap(e.cityID,e.cityName);
            		rt =false;
        		} */
//        		return e.update && e.ratio==100;    
         }
		
        if(rt){ 
        	
        		tryTimes =0;//initilize the trytimes for the cityid
            	 downloadCityMap(cityId,cityName);
        	  }
        
        importFromSDCard();
		
		
	}
	
	
	
	boolean downloadCityMap(int cityId,String cityName){
		 app.isOfflimeMapWorking = true;
		mOffline.start(cityId); 
//		Toast.makeText(this, "开始下载离线地图. cityid: "+cityId, Toast.LENGTH_SHORT)
//		          .show();
		QLog.getLogger().d(dTAG, TAG+" 开始下载离线地图. cityid: "+cityId );	 
        long totalTime =0;
        int lastPcent =0;
        int dPcent =0;
		while( ratio<100 && Utils.getNetworkType(this) == QiYouConstant.NETWORK_TYPE_WIFII
				&&totalTime<1000*20){
			if(lastPcent==0)lastPcent=ratio;
			
       	 try {
       		 QLog.getLogger().d(dTAG, TAG+ " " +cityName +" Offline map  download percent: " + ratio );	 
			Thread.sleep(1000); 
			
		  } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			Utils.logStackTrace(e, TAG);
			}
       	 dPcent +=ratio -lastPcent  ;
       	 if(ratio==lastPcent)totalTime+=1000;
       	 lastPcent =ratio;
       	
   	    }  
	 
		QLog.getLogger().d(dTAG, TAG+" Offline map  download percent: " + dPcent );
	 	if(ratio ==100){
			String msg = String.format("成功下载并导入 %s 离线地图",cityName);	
//		 	Toast.makeText(this, msg , Toast.LENGTH_SHORT).show();
		 	QLog.getLogger().d(dTAG, TAG+ " "+msg);
		  
		    app.isOfflimeMapWorking = false;
	 	}else
	 	{  
	 			QLog.getLogger().d(dTAG, TAG+String.format("  本次新下载了%d" ,lastPcent -ratio));
	 			if(lastPcent ==ratio && ratio==0){
	 				mOffline.remove(cityId);	 				
	 				QLog.getLogger().d(dTAG, TAG+" 删除原有下载,重新开始下载");
	 				tryTimes+=1;
	 				if(tryTimes<3)
	 					downloadCityMap(cityId,cityName); 
	 				
	 			}
	 		
	 	}
	
	 	QLog.getLogger().d(dTAG, TAG+ " 本次处理结束."); 
	 	app.setlastOffMapRequestTime();
	 	return true;
	}
	
  void importFromSDCard( ){
//		int num = 
//		mOffline.scan();
		/*String msg = "";
		if ( num == 0){
			msg = "没有导入离线包，这可能是离线包放置位置不正确，或离线包已经导入过";
		}
		else{
		   msg = String.format("成功导入 %d 个离线包，可以在下载管理查看",num);	
		}
//		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
		QLog.getLogger().d(dTAG, TAG+" "+ msg );*/
	} 
	
	private int search(String cityName ){
		int cityId= -1;
		ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityName);
		if (records != null && records.size() == 1)
			cityId = records.get(0).cityID;

		return cityId;  
	}
	 
	
	void initialOffMap(){
// 	    mMapView = new MapView(new Activity());
		
		QLog.getLogger().d(dTAG, " offmap update... initializing mapview");
		
	/*	mMapView = app.mMapview;
		
		if(mMapView ==null){
			stopSelf();
			return;
		}*/
		
//        mMapController = mMapView.getController();
        
        mOffline = new MKOfflineMap();    
        /**
         * 初始化离线地图模块,MapControler可从MapView.getController()获取
         */
        
//        mOffline.init(mMapController, this); 
        
        mOffline.init(/*mMapController,*/ mylistener);
        
        
        //获取已下过的离线地图信息
        localMapList = mOffline.getAllUpdateInfo();
        if ( localMapList == null ){
            localMapList = new ArrayList<MKOLUpdateElement>();	
        } 
	}

	
	MKOfflineMapListener	mylistener = new MKOfflineMapListener() {
    	
    	@Override
    	public void onGetOfflineMapState(int type, int state) {
    	    switch (type) {
            case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                {
                    MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                    if ( update != null ){
    					ratio =update.ratio;
//    				    stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio));
//    				    updateView();
    				}
                }
                break;
            case MKOfflineMap.TYPE_NEW_OFFLINE:
//                QLog.getLogger().d(dTAG, String.format("add offlinemap num:%d", state));
                break;
            case MKOfflineMap.TYPE_VER_UPDATE:
//                QLog.getLogger().d(dTAG, String.format("new offlinemap ver"));
                break;
            } 

    	}
    	 
        
    };
    
    
	/*@Override
	public void onGetOfflineMapState(int type, int state) {
		switch (type) {
		case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
			{
				MKOLUpdateElement update = mOffline.getUpdateInfo(state);
				//处理下载进度更新提示
				if ( update != null ){
					ratio =update.ratio;
//				    stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio));
//				    updateView();
				}
			}
			break;
		case MKOfflineMap.TYPE_NEW_OFFLINE:
			//有新离线地图安装
			QLog.getLogger().d("OfflineDemo", String.format("add offlinemap num:%d", state));
			break;
		case MKOfflineMap.TYPE_VER_UPDATE:
		    // 版本更新提示
            //	MKOLUpdateElement e = mOffline.getUpdateInfo(state);
			
			break;
		}
		 
	}*/
}
