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

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;
 
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.Statics_bean;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackAvStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.enums.WorkingTrackType;
import com.qiyou.mb.android.utils.enums.wpFlag;
import com.qiyou.mb.android.utils.log.QLog;

public class GpxDetail_fragment extends TrackDetail_fragment {
	@Override
	public void setFTag(){
		TAG="com.qiyou.GpxDetail_fragment";
	}
	public static String getFTag(){
		return "com.qiyou.GpxDetail_fragment";
	}
	@Override
	public String getCurrentTag(){
		return "com.qiyou.GpxDetail_fragment";
	}
	
	
	public GpxDetail_fragment() {
		// TODO Auto-generated constructor stub
		workingTrackType= WorkingTrackType.GPX;
	}

 	public static GpxDetail_fragment newInstance(int inType,int trackId,boolean isWebQuery)
	{
		
 		GpxDetail_fragment f = new GpxDetail_fragment();
		Bundle args = new Bundle(); 
//	    args.putString(QiYouConstant.EXTRA_KEY_ID, trackId);
//	    args.putString(QiYouConstant.EXTRA_KEY_TYPE, inType);
	    args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId);
	    args.putInt(QiYouConstant.EXTRA_KEY_TYPE, inType);
	    args.putBoolean(QiYouConstant.EXTRA_KEY_WEB_REQUEST, isWebQuery);
	    f.setArguments(args);
	    return f;
	}
	 
	private TextView txt_creator;
	private TextView txt_src;
	private TextView txt_routeType;
    int svrNumber;
	private Button btn_edit;
	private Button btnDelWebTrack;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
//		if(activity.app.currentTrack!=null)app.initialStatTrack(activity.app.currentTrack.getTrackBean().getType().toInt());
		QLog.getLogger().d(dTAG, TAG+" onCreate, app Current trackid is: "+ app.getCurrentTrack().getTrackBean().getTrackId());
		inflat_source =R.layout.gpx_detail_fragment;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		this.setWorkingTrack();
		if(mTrack!=null && mTrack.isLushu())
			inflat_source =R.layout.gpx_lushu_fragment;
		vContainer= super. onCreateView( inflater,  container, savedInstanceState);
//		if(!isWebRequest){
//			rdGroup.setVisibility(View.GONE);
//		}
		txt_creator =(TextView)vContainer.findViewById(R.id.td_textView_creator);
		txt_src =(TextView)vContainer.findViewById(R.id.td_textView_src);
		
		 chk_showGpx=(CheckBox)vContainer.findViewById(R.id.chk_showGpxDetail);
		 btn_edit=(Button)vContainer.findViewById(R.id.rt_btn_edit);
		 btnDelWebTrack =(Button)vContainer.findViewById(R.id.td_btnDeleteTtrack);
		 btnDelWebTrack.setOnClickListener(ButtonOnClickListener);
	
		 btn_edit.setOnClickListener( new OnClickListener() { 
			    @Override
				public void onClick(View view) {
			    	if(trackId>0)
			    		activity.showRoute(trackId);
			    	}
			    }
			 );
		 btn_edit.setVisibility(View.VISIBLE);
 
		 
		  lv = (ListView) vContainer.findViewById(R.id.tent_list);  
		 
		   btnImport = (Button) vContainer.findViewById(R.id.td_btnImport); 
		   btnImport.setOnClickListener(ButtonOnClickListener);
		   
		   txt_routeType =(TextView)vContainer.findViewById(R.id.td_textView_routeType);
		   
		return vContainer;
	}
		 
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) { 
		
		if(isWebRequest){
			currentStat=new Statics_bean(app.getCurrentTrack().getTrackBean());
//			chk_showGpx.setEnabled(false);
			chk_showGpx.setVisibility(View.GONE);
			super.onActivityCreated(savedInstanceState);
			svrNumber = this.trackId;
			return;
		}
		super.onActivityCreated(savedInstanceState);
		
		chk_showGpx.setChecked(app.getGpxShowingTracks().contains(trackId));
//		chk_showGpx.setOnCheckedChangeListener(gpxCheckboxListener);
		chk_showGpx.setOnClickListener(new OnCheckBoxClickListener());
	   
	}	
	
	
	class OnCheckBoxClickListener implements OnClickListener {  
	      
        @Override  
        public void onClick(View view) {  
//            CheckBox checkBox = (CheckBox) view;  
            QLog.getLogger().d(dTAG, "gpx_checkbox checked?" +chk_showGpx.isChecked());
			 if(mTrack_bean==null || mTrack_bean.getTrackId()<=0)return;
			 activity.app.setGpxShowingTracks(String.valueOf( mTrack_bean.getTrackId()), chk_showGpx.isChecked()); 
			 if(chk_showGpx.isChecked() &&mTrack!=null){
				 activity.app.getTrackCache().put(Integer.valueOf(mTrack_bean.getTrackId()), mTrack);
			 } 
  
        }  
  
    }  
  
	 @Override
	 protected void setTrackDesc(){	 
	 	super.setTrackDesc(); 
	 	boolean canEdit=trackId>0 && !isWebRequest;
	 	this.btnNewCate.setEnabled(canEdit);
	 	 
	 	this.mNameEdit.setEnabled(canEdit);
	 	mDescEdit.setEnabled(canEdit);
 	    this.spDetailTrackType.setEnabled(canEdit && inType!=TrackType.GPX.toInt()) ;
	 	
		  int visible = canEdit?View.VISIBLE:View.INVISIBLE;
		  if(btnSave!=null){
		     btnSave.setVisibility(visible);
	    	 btnSave.setOnClickListener(ButtonOnClickListener);
		     }
		
//		  this.btnUpload.setVisibility(visible);
	    
	 	 }

	@Override
	 protected void validEditButtons(){
		super.validEditButtons();
		 btn_edit.setEnabled(td_btn_export.isEnabled());
		 if(td_btnContinue!=null){
	    	  td_btnContinue.setVisibility(View.GONE);
	      }
	}
	@Override
	protected void setTrackDetailMax(){
		
	}
	@Override
	protected void setTrackDetailAv(){
		
	}
	@Override
	protected void setLastTrackDetai(){
		
	}
	@Override
	protected void setTrackDetail1(){
		super.setTrackDetail1();
		try{
    	 if(currentStat!=null ){
    		if(txt_creator!=null )
				txt_creator.setText(currentStat.getCreator()); 
    		if(txt_src!=null )
				txt_src.setText(currentStat.getSrc()); 
    	}
    	 
    	txt_creator.setText(mTrack.getTrackBean().getUserid()==activity.app.user.getUserbean().getId()?
    			activity.app.user.getUserbean().getUserName():currentStat.getCreator());
    	
    	
    	
    	
    	
    	if(txt_routeType!=null){
    	  txt_routeType.setText(getRouteType(mTrack.getTrackBean().getIsCheckedIn()));
    	}
    	
    	if(mTrack.getTrackBean().getSvrNumber()>0 ||isWebRequest){ 
    		
     		txt_src.setText(QiYouConstant.BASE_URL+"gpx/"+mTrack.getTrackBean().getSvrNumber()+".gpx");
     		
//     		if(TextUtils.isEmpty(txt_creator.getText())){
//     			txt_creator.setText(mTrack.getTrackBean().getUserName());
//     		}
//     		
			setUserLinkSpanTxt(txt_creator,mTrack.getTrackBean().getUserid(),mTrack.getTrackBean().getUserName());

     		
     		
     		
     		
    	}
    	
    	
    	if(mTrack_bean.getType()==TrackType.GPX){
    		showTentData();
    	}
    	
			
		}catch(Exception e){
			Utils.logStackTrace(e, dTAG);
		}
		
	}
	
	@Override
	protected void locationToTrackEnd(){
		super.locationToTrackEnd();
    	if(mTrack_bean ==null  )return;
		 
           top_sptime.setText(Utils.getTimeCnt(mTrack_bean.getTotalTime(), false)  );
//		   top_speed.setText("_._");
		   float avs =mTrack_bean.getTavs();
		   top_speed.setText((avs>0?String.format("%.2f",avs):"--") );
	}
	/*@Override
	protected void setStaticMap()
	  {
//		if(staticMapImg.getVisibility()==View.VISIBLE)return;
	    this.staticMapImg.setVisibility(View.GONE);
	    if (!this.isWebRequest) {
	      super.setStaticMap();
	      return;
	    }
	   
	    String webStaticUrl=Utils.getBaiduStaticMapUrl(mTrack);;
	    QLog.getLogger().d(dTAG, " webStaticUrl is:"+webStaticUrl);
	    QLog.getLogger().i(dTAG, " webStaticUrl is:"+webStaticUrl);
	      if (!TextUtils.isEmpty(webStaticUrl) && this.staticMapImg != null) {
	        this.IL.DisplayImage(webStaticUrl, this.staticMapImg);
		    this.staticMapImg.setVisibility(View.VISIBLE);
	      }
	     
	  }
	*/
	/*@Override 
	void uploadTrack(Track track){  //导入web 记录
		if(!isWebRequest){
			super.uploadTrack(track);
			return;
		}
	 if(isForShare) return;
	 track.getTrackBean().setTrackId(0);
	 track.getTrackBean().setType(TrackType.GPX);
//	 track.getTrackBean().setSrc(track.getTrackBean().getSrc());
	 String creator=track.getTrackBean().getCreator();
	 creator=TextUtils.isEmpty(creator)||creator.equalsIgnoreCase("null")?track.getTrackBean().getUserName()
			 							:creator+" -- "+track.getTrackBean().getUserName();
 	 track.getTrackBean().setCreator(creator);
 	 track.getTrackBean().setSvrNumber(0);
	 activity.app.getImportedGpx().clear();
	 
	 activity.app.getImportedGpx().add(track);
	 activity.app.impGpx();
	 showNotes("导入任务已提交,您可以在 历史-->路书 列表中找到导入到路线。");
	 this.btnUpload.setEnabled(false);
	 }*/
	
	void importTrack(){
	 
	 mTrack_bean.setTrackId(0);
	 mTrack_bean.setType(TrackType.GPX);
//	 track.getTrackBean().setSrc(track.getTrackBean().getSrc());
	 String creator=mTrack_bean.getCreator();
	 creator=TextUtils.isEmpty(creator)||creator.equalsIgnoreCase("null")?mTrack_bean.getUserName()
			 							:creator+" -- "+mTrack_bean.getUserName();
	 mTrack_bean.setCreator(creator);
	 mTrack_bean.setSvrNumber(0);
	 activity.app.getImportedGpx().clear();
	 
	 activity.app.getImportedGpx().add(mTrack);
	 activity.app.impGpx();
	 showNotes("导入任务已提交,您可以在 菜单-->我的记录-->路书 列表中找到导入到路线。");
	 this.btnImport.setEnabled(false);
	}
	
	@Override
	  void updateUploadButton(){  
		   
		super.updateUploadButton();
		  boolean canDel =mTrack_bean.getUserid()==activity.app.user.getUserbean().getId()
				  ||this.isAdmin();

		  
		  
		  if(isWebRequest){
			  btnImport.setVisibility(View.VISIBLE);
//			  btnUpload.setText("导入");
			  if(btnSave!=null){
				  this.btnSave.setEnabled(false);
 				  btnUpload.setVisibility(View.INVISIBLE);
			  }
//			  this.btnExportFm.setEnabled(false); 
//			  this.btnDel.setEnabled(false);
			  this.btnDel.setEnabled(canDel);
			  int status =mTrack_bean.getAvStatus()==TrackAvStatus.PRIVATE? 
					  R.string.track_edit_public: R.string.track_edit_private;
			  
			  btnDel.setText(status); 
			  
			  btnDelWebTrack.setVisibility(mTrack_bean.getSvrNumber() >0 && mTrack_bean.getUserid() == app.user.getUserbean().getId()?View.VISIBLE : View.GONE);
			  btnDelWebTrack.setEnabled(mTrack_bean.getUserid() == app.user.getUserbean().getId() );
			/*  if(app!=null&&app.mStatistics!=null&&app.mStatistics.getExistedSvrNos().contains(Integer.valueOf(trackId))){
				  btnImport.setEnabled(false); 
			  } */
				 
		  }
		  
		  else{
			  btnImport.setVisibility(View.GONE);
			  if(btnUpload!=null){
				  btnUpload.setEnabled(canDel);
			  }
		  } 
		  
 	  }
		@Override
	  protected void startNavi(boolean isSimulation){	  
		super.startNavi(isSimulation);
		if(!isSimulation &&this.isWebRequest){
			app.setLastNavWeb(String.valueOf(svrNumber)+mTrack.getTrackBean().getLastdbTime());
		}
	  }
		
		
		@Override
		protected void  updateTrackAvstatus(){
			if(this.isWebRequest){
			
			TrackAvStatus status =mTrack_bean.getAvStatus()==TrackAvStatus.PRIVATE? 
					TrackAvStatus.PUBLIC:TrackAvStatus.PRIVATE;
			mTrack_bean.setAvStatus(status);
			updateTrackStatus(mTrack_bean.getSvrNumber(),status); 
			return;
			}
			
			super.updateTrackAvstatus();
			
			
		}
		
//		@Override
//		void updateUIOnRequestResonsed(String method) {
////			btnSubmit.setEnabled(true);
//			updateUploadButton();
//		}
 
	@Override
		public void onResume() {
			super.onResume();
		 
			}
			
	 
	  private List<Map<String, String>> mData;
	  private ListView lv = null;  
	 
	  void showTentData(){ 
		  
		  if(mData==null){ 
			  Waypoint_bean lastWb =mTrack_bean.getStartWp().getWb();
			  int i=0;
			  for(Waypoint_bean wb:mTrack_bean.getRoadWps()){
				  if(wb.getTurnFlag()!=wpFlag.TENT) continue;
				  
				  HashMap<String, String>  data = new HashMap<String, String>();
				  data.put("number", "D" + ++i );
				  data.put("icon", String.valueOf(i>1?R.drawable.icon_tent:R.drawable.icon_sstart));
				  String startgeo="              ";
				 
				  if(lastWb.getGeo()!=null){
					  startgeo=(TextUtils.isEmpty( lastWb.getGeo().getCity())?Utils.getProvince(lastWb.getGeo().getProvince()):lastWb.getGeo().getCity()+"，")
							  +lastWb.getGeo().getDistrict();
					  QLog.getLogger().d(dTAG, "lastWb.getGeo().getProvince:"+ lastWb.getGeo().getProvince());
					  QLog.getLogger().d(dTAG, "lastWb.getGeo().getCity():"+ lastWb.getGeo().getCity());
					  QLog.getLogger().d(dTAG, "lastWb.getGeo().getDistrict():"+ lastWb.getGeo().getDistrict());
					  
					 
				  }
				   data.put("start", Utils.getGeoDistrict(startgeo,9)); 
				   String endgeo="              ";
				  if(wb.getGeo()!=null){ 
					  endgeo= (TextUtils.isEmpty( wb.getGeo().getCity())?Utils.getProvince(wb.getGeo().getProvince()):wb.getGeo().getCity()+"，")
							  +wb.getGeo().getDistrict();
					  QLog.getLogger().d(dTAG, "wb.getGeo().getProvince:"+ wb.getGeo().getProvince());
					  QLog.getLogger().d(dTAG, "wb.getGeo().getCity():"+ wb.getGeo().getCity());
					  QLog.getLogger().d(dTAG, "wb.getGeo().getDistrict():"+ wb.getGeo().getDistrict());
					
				  }
				    data.put("to", Utils.getGeoDistrict(endgeo,9)  );
				  data.put("distance", Utils.getFormatedDistance((wb.getSumDist()- lastWb.getSumDist())) );
				  data.put("time", String.valueOf(wb.getTime()));
				  data.put("cmnt", wb.getComment());
				  lastWb=wb;
				  if(mData==null)
					  mData =new ArrayList<Map<String, String>>();
				  mData.add(data);
			  }
			  
			  if(mData!=null){
				  
				  
				  HashMap<String, String>  data = new HashMap<String, String>();
				  data.put("number", "D" + ++i );
				  data.put("icon", String.valueOf(R.drawable.icon_send));
				  String startgeo="              ";
				  if(lastWb.getGeo()!=null){
					  startgeo=(TextUtils.isEmpty( lastWb.getGeo().getCity())?Utils.getProvince(lastWb.getGeo().getProvince()):lastWb.getGeo().getCity()+"，")+lastWb.getGeo().getDistrict();
					  
				  }
				  data.put("start",Utils.getGeoDistrict(startgeo,9)   ); 
				  String endgeo="              ";
				  if(mTrack_bean.getLastWp().getWb().getGeo()!=null){ 
					  endgeo =(TextUtils.isEmpty( mTrack_bean.getLastWp().getWb().getGeo().getCity())?Utils.getProvince(mTrack_bean.getLastWp().getWb().getGeo().getProvince()):mTrack_bean.getLastWp().getWb().getGeo().getCity()+"，")
							  +mTrack_bean.getLastWp().getWb().getGeo().getDistrict();
					
				  }
				  data.put("to",Utils.getGeoDistrict(endgeo,9)    );
				  data.put("distance", Utils.getFormatedDistance((mTrack_bean.getLastWp().getWb().getSumDist()- lastWb.getSumDist())) );
				  data.put("time", String.valueOf(mTrack_bean.getLastWp().getWb().getTime()));
				  data.put("cmnt", mTrack_bean.getLastWp().getWb().getComment());
				  mData.add(data);
			  }
			  
			  
			  
			   
		  }
		  
		  if(mData==null)return;
		  
			 
		   QSimpleAdapter  adapter = new QSimpleAdapter(activity,mData,R.layout.tent_list_detail,
						new String[]{"number","icon","start","to","distance","time"},
						new int[]{R.id.tent_number,R.id.tent_img, R.id.tent_from,R.id.tent_to,R.id.tent_km,R.id.tent_time}); 
		    
		    adapter.setViewBinder( new ViewBinder(){
		    	@Override
				public boolean setViewValue(View view, Object data,String textRepresentation) {    		
		    			    		
		    		view.setVisibility(View.VISIBLE);
		    		if(data ==null || TextUtils.isEmpty(data.toString())){
		    			view.setVisibility(View.GONE);
		    			return true;
		    		} 
		    		 else
		            if( view instanceof com.qiyou.mb.android.utils.image.QimageView  && data instanceof String){  
		            	com.qiyou.mb.android.utils.image.QimageView iv = (com.qiyou.mb.android.utils.image.QimageView) view;    
		            	iv.setBackgroundResource(Integer.valueOf(data.toString())); 
		                return true;    
		            } else if(view.getId()==R.id.tent_time){ 
		            	view.setVisibility(View.GONE);
		    			return false;  //if return true then will no value set to the view.
		            }
		            return false;    
		        }    
		    });    
		    
		  
		    lv.setAdapter(adapter);  
		    adapter.setSelectItem(selectedFoodmarkItem);
		    lv.setSelection(selectedFoodmarkItem);
		    setListViewHeightBasedOnChildren(lv);
//		    lv.smoothScrollToPosition(selectedFoodmarkItem);
//		    lv.smoothScrollToPositionFromTop(selectedFoodmarkItem, 50);
	 }
	  
	  //更新个人云端记录是否可见
	  @Override	  
	  void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{
		  if(!isWebRequest){
				super.processJsonObject(  method,jsonObject,  msg);
				return;
			}
			 pirntCookies(); 
			 QLog.getLogger().d(dTAG, "to update avstatus:" +jsonObject.toString());
			 boolean sucess =jsonObject!=null;//&& jsonObject.has(QiYouConstant.JSONOBJECT_KEY )
//					 			&& TextUtils.isEmpty(jsonObject.get(QiYouConstant.JSONOBJECT_KEY).toString());
			 if(sucess){
				 
				 if (mTrack_bean.getAvStatus() == TrackAvStatus.DELETED){
					 showNotes("删除成功！");
					 activity.isNeedFresh = true;
					 this.onBack();
				 }
				 
				 
				 showNotes("更新成功！");
				 Track_bean tb=(Track_bean) Utils.getGsonObject(jsonObject.toString(), Track_bean.class);
//				 String lastdbupdated=jsonObject.get(QiYouConstant.JSONOBJECT_KEY).toString();
				 app.updateTrackAvStatus(mTrack_bean.getTrackId()); //update local record
				 updateUploadButton();
 
				  try { //update local gpx cache file.
					Utils.writeSDFile(getCacheFileName(QiYouConstant.GPX_CACHE_PATH,String.valueOf(svrNumber)+tb.getLastdbTime()), mTrack_bean.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }
			 else
				 showNotes("未知错误");  
			 
		 }
	  
	  
	  /*
	  @Override
	  void initialCateViews(){
		  
	  }
	  @Override
	  void initialEditViews(){
		  mDescEdit = (EditText) vContainer.findViewById(R.id.td_edit_desc);	
		  mDescEdit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
		  td_track_sumary = (TextView) vContainer.findViewById(R.id.td_track_sumary);

			
	  }
	  @Override
	  protected void showCategoryList(com.qiyou.mb.android.ui.fragments.InnerGridView cateLv , ScrollView textContainer ){
		  
	  }*/
	  
	  private String getRouteType(int type) {	  
			switch(type){
			case 0: return "骑行";
			case 1: return "徒步";
			case 2: return "机动";
			default:return "骑行";
			}
	  }
}
