package com.qiyou.mb.android.ui.fragments;

import java.util.ArrayList;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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.baidu.mapapi.map.MapView;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.ui.fragments.QiyouFragment;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;

public class OfflineMaps_fragment extends QiyouFragment {
	
//	public static String TAG="com.qiyou.OfflineMaps_fragment";	
//	public static String dTAG="com.qiyou";
	
//	implements MKOfflineMapListener {

	 
		
	@Override
	public void setFTag(){
		TAG="com.qiyou.OfflineMaps_fragment";
	}
	
	public static String getFTag(){
		return "com.qiyou.OfflineMaps_fragment";
	}
	@Override
	public String getCurrentTag(){
		return "com.qiyou.OfflineMaps_fragment";
	}
//	MainActivity  activity;
	private View vContainer;
	boolean isPlayback =false;
	 
//	private MapView mMapView = null;
	private MKOfflineMap mOffline = null;
	private TextView cidView;
	private TextView stateView;
	private EditText cityNameView;
//	private MapController mMapController = null;
	/**
	 * 宸蹭笅杞界殑绂荤嚎鍦板浘淇℃伅鍒楄〃
	 */
	private ArrayList<MKOLUpdateElement>localMapList =null;
	private LocalMapAdapter lAdapter = null;
	
	public static OfflineMaps_fragment newInstance( )
	{
		OfflineMaps_fragment f = new OfflineMaps_fragment(); 
	    return f;
	}
    
    
    
    public OfflineMaps_fragment() {
		// TODO Auto-generated constructor stub
	}
    
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
			activity.updateActionBarTitle(R.string.frg_offlinemap);	
//		  activity=(MainActivity)getActivity();
//		  activity.app.currentActiveFragment =TAG; 
		  vContainer = inflater.inflate(R.layout.offlinemaps_fragment, container, false);	 
	       initialView(); 
	      
	       this.vContainer. setOnTouchListener(new OnTouchListener() {
		    @Override
		    public boolean onTouch(View v, MotionEvent event) {
 		        Utils.hideSoftKeyboard(activity);
		        return false;
		    }
	       });
		 
		return vContainer;
		}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	    
		     
		}

	private Button btnStart;
	private Button btnStop; 
	private Button btnOffSearch;
//	private Button btnOffScan;
//	private Button btnDel;
//	private Button btnCityList;
//	private Button btnlcoalMapList;
	void initialView(){
		
//	    mMapView = activity.app.mMapview;
	    
//        mMapController = mMapView.getController();
        
//        mOffline = new MKOfflineMap();    
        /**
         * 初始化离线地图模块,MapControler可从MapView.getController()获取
         */
        /*mOffline.init(mMapController, new MKOfflineMapListener() {
            @Override
			public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                    {
                        MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                        //mText.setText(String.format("%s : %d%%", update.cityName, update.ratio));
                      //处理下载进度更新提示
        				if ( update != null ){
        				    stateView.setText(String.format("%s : %s , %d%%", update.cityName,formatDataSize(update.size), 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;
                }    
                  }
        }
        ); 
  		localMapList = mOffline.getAllUpdateInfo();
        if ( localMapList == null ){
            localMapList = new ArrayList<MKOLUpdateElement>();	
        }
        */
		
		initialOffMap();
		
        ListView localMapListView = (ListView)vContainer.findViewById(R.id.localmaplist);
        lAdapter = new LocalMapAdapter();
        localMapListView.setAdapter(lAdapter);
        
        cidView       = (TextView)vContainer.findViewById(R.id.off_cityid);
		cityNameView  = (EditText)vContainer.findViewById(R.id.off_city);
		stateView     = (TextView)vContainer.findViewById(R.id.off_state);
        
        btnStart = (Button) vContainer.findViewById(R.id.off_start);
        btnStop = (Button) vContainer.findViewById(R.id.off_stop);
//        btnDel =(Button) vContainer.findViewById(R.id.off_del);
        btnOffSearch = (Button) vContainer.findViewById(R.id.off_search); 
//        btnOffScan = (Button) vContainer.findViewById(R.id.off_scan);
//        btnCityList  = (Button) vContainer.findViewById(R.id.off_clButton);
//         btnlcoalMapList = (Button) vContainer.findViewById(R.id.off_localButton);
//         btnlcoalMapList.setOnClickListener(ButtonOnClickListener);	
    	
//        btnCityList.setOnClickListener(ButtonOnClickListener);	
        btnStart.setOnClickListener(ButtonOnClickListener);	
        btnStop.setOnClickListener(ButtonOnClickListener);	
//        btnOffScan.setOnClickListener(ButtonOnClickListener);	
        btnOffSearch.setOnClickListener(ButtonOnClickListener);	
//        btnDel.setOnClickListener(ButtonOnClickListener);	 
        if(activity.app.getGEOinfo()!=null){
        	cidView.setText(activity.app.getGEOinfo().getCityId());
        	cityNameView.setText(activity.app.getGEOinfo().getCity());
        }
        if(TextUtils.isEmpty(cidView.getText())){
        	cidView.setText("224");
//        	cityNameView.setText("苏州");
        }
        this.btnStart.setEnabled(false);
		 this.btnStop.setEnabled(false);
	}
	
	

	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;
            } */
    		
    		  switch (type) {
              case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                  {
                      MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                      //mText.setText(String.format("%s : %d%%", update.cityName, update.ratio));
                    //处理下载进度更新提示
      				if ( update != null ){
      				    stateView.setText(String.format("%s : %s , %d%%", update.cityName,formatDataSize(update.size), 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;
              }    
    		  

    	} 
    	 
        
    };
    
    
    
	protected OnClickListener  ButtonOnClickListener = new OnClickListener() {
	    @Override
		public void onClick(View view) {
	    	switch (view.getId() ){
	    		case R.id.off_start: {start();break;}	    		
	    		case R.id.off_search:{search();break;}
//	    		case R.id.off_scan:{importFromSDCard();break;}
	    		case R.id.off_stop:{stop();break;}
//	    		case R.id.off_del:{remove();break;}
//	    		case R.id.off_clButton:{clickCityListButton();break;}
//	    		case R.id.off_localButton:{clickLocalMapListButton();break;}
	    	}
	    			
	    }
	    };
	    
	    
	
		/**
		 * 搜索离线需市
		 * @param view
		 */
//		public void search(View view){
		public void search( ){
			ArrayList<MKOLSearchRecord> records = mOffline.searchCity(cityNameView.getText().toString());
			if (records == null || records.size() != 1){
			 this.btnStart.setEnabled(false);
			 this.btnStop.setEnabled(false);
			 return;
			}
			 this.btnStart.setEnabled(true);
			 this.btnStop.setEnabled(true);
			cidView.setText(String.valueOf(records.get(0).cityID));
			stateView.setText(String.format("离线包大小%s", formatDataSize(records.get(0).size)));
		}
		
		/**
		 * 切换至下载管理列表
		 * @param view
		 */
//		public void clickLocalMapListButton(View view){
		public void clickLocalMapListButton(){
//			LinearLayout cl = (LinearLayout)vContainer.findViewById(R.id.off_citylist_layout);
//			LinearLayout lm = (LinearLayout)vContainer.findViewById(R.id.off_localmap_layout);
//			lm.setVisibility(View.VISIBLE);
//			cl.setVisibility(View.GONE);
		}
		/**
		 * 开始下载
		 * @param view
		 */
//		public void start(View view){
			public void start(){
			int cityid = Integer.parseInt(cidView.getText().toString());
			mOffline.start(cityid);
			clickLocalMapListButton();
			Toast.makeText(activity, "开始下载离线地图. cityid: "+cityid, Toast.LENGTH_SHORT)
			          .show();
		}
		/**
		 * 暂停下载
		 * @param view
		 */
//		public void stop(View view){
			public void stop( ){
			int cityid = Integer.parseInt(cidView.getText().toString());
			mOffline.pause(cityid);
			Toast.makeText(activity, "暂停下载离线地图. cityid: "+cityid, Toast.LENGTH_SHORT)
			          .show();
		}
		/**
		 * 删除离线地图
		 * @param view
		 */
//		public void remove(View view){
		 public void remove(){
			int cityid = Integer.parseInt(cidView.getText().toString());
			mOffline.remove(cityid);
			Toast.makeText(activity, "删除离线地图. cityid: "+cityid, Toast.LENGTH_SHORT)
			          .show();
		}
		/**
		 * 从SD卡导入离线地图安装包
		 * @param view
		 */
//	    public void importFromSDCard(View view){
		/* public void importFromSDCard( ){
			int num = mOffline.scan();
			String msg = "";
			if ( num == 0){
				msg = "没有导入离线包，这可能是离线包放置位置不正确，或离线包已经导入过";
			}
			else{
			   msg = String.format("成功导入 %d 个离线包，可以在下载管理查看",num);	
			}
			Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
		}*/
	    /**
	     * 更新状态显示 
	     */
	    public void updateView(){
	    	localMapList = mOffline.getAllUpdateInfo();
	        if ( localMapList == null ){
	            localMapList = new ArrayList<MKOLUpdateElement>();	
	        }
	    	lAdapter.notifyDataSetChanged();
	    }
		
		

		@Override
		public void onPause() {
			
			int cityid = Integer.parseInt(cidView.getText().toString());
			mOffline.pause(cityid);
//	        mMapView.onPause();
	        super.onPause();
	    }
	    
	    @Override
	    public void onResume() {
//	        mMapView.onResume();
	        super.onResume();
	    }
	    
	    
	    public  String formatDataSize(int size) {
	        String ret = "";
	        if (size < (1024 * 1024)) {
	            ret = String.format("%dK", size / 1024);
	        } else {
	            ret = String.format("%.1fM", size / (1024 * 1024.0));
	        }
	        return ret;
	    }

	    class LocalMapAdapter extends BaseAdapter{

			@Override
			public int getCount() {
				return localMapList.size();
			}

			@Override
			public Object getItem(int index) {
				return localMapList.get(index);
			}

			@Override
			public long getItemId(int index) {
				return index;
			}

			@Override
			public View getView(int index, View view, ViewGroup arg2) {
				MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
			    view = View.inflate(activity, R.layout.offline_localmap_list,null);
			    initViewItem(view,e);
				return view;
			}
			
			void initViewItem(View view , final MKOLUpdateElement e){
				Button btnUpdate = (Button)view.findViewById(R.id.off_btnupdate);
				Button remove  = (Button)view.findViewById(R.id.off_remove); 
				TextView title = (TextView)view.findViewById(R.id.off_title);
				TextView update = (TextView)view.findViewById(R.id.off_update);
				TextView ratio = (TextView)view.findViewById(R.id.off_ratio);
				ratio.setText(e.ratio+"%");
				title.setText(e.cityName);
				if ( e.update){
					update.setText("待更新");
				}
				else{
					update.setText("最新");
				}
				if (  e.update || e.ratio != 100 ){
					btnUpdate.setEnabled(true);
					 if(e.ratio != 100){
						 btnUpdate.setText("继续");
					 }
				}
				else{
					btnUpdate.setEnabled(false);
				}
				remove.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View arg0) {				
						 mOffline.remove(e.cityID);
	                     updateView();
					}
				});
				btnUpdate.setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						mOffline.start(e.cityID);
					}
				}); 
			}
			
		}

		@Override
		public boolean isShowBottomTabs() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void setTabOnFiling() {
			// TODO Auto-generated method stub
			
		}
}
