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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.RequestParams;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.basic.GEO_bean;
import com.qiyou.mb.android.beans.basic.Group_bean;
import com.qiyou.mb.android.beans.basic.Media;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.enums.mediaType;
import com.qiyou.mb.android.utils.server.RestMethods;

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

import java.io.FileNotFoundException;
import java.io.IOException;

public class GroupDetail extends ActivityDetail {
	
	/*@Override
	public String getCurrentTag() {
		// TODO Auto-generated method stub
		return TAG;
	}*/

	@Override
	public void setFTag() {
		// TODO Auto-generated method stub
		TAG="com.qiyou.GroupDetail";
//		FirstTabTextColor= getResources().getColorStateList(R.color.red);    
//		FirstTabBackGround=R.drawable.icon_group;
	}
	 
	public static String getFTag() {
		return "com.qiyou.GroupDetail";
	}
	
	
	
	private Group_bean currentGroup ;
	public static GroupDetail newInstance(Group_bean  group) {
		
		GroupDetail f = new GroupDetail();
	    f.currentGroup =group;
	    return f;
	}
	
	public static GroupDetail newInstance() {
		
		GroupDetail f = new GroupDetail(); 
	    return f;
	}
	
	public void setCurrentGroup(Group_bean  group){
		currentGroup =group;
//		initialWebQuery();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		super.BBScate = BBSCate.GROUP.toInt();
	}

	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {   
		 
		 if (currentGroup == null) {	      
			  
			 currentGroup = new Group_bean();
		     
		    }
		 
//		  svrNumber =currentGroup.getId();
		  
		  
		  
		     title =currentGroup.getId()>0 ?  getResources().getString(R.string.frg_groupdetail)
		    		 +"｜"+currentGroup.getName()
		    		 			: getResources().getString(R.string.frg_groupnew);
		    
		     
		currentLayout =R.layout.group_detail_edit;
		vContainer = inflater.inflate(currentLayout, container, false);
		
	
		initialViews( ); 
//	 	initialLLViews();
//		 initialMapview();
		
		return vContainer;
		}		
	
	
	
	/*@Override
	void initialMapview(){
		super.initialMapview();
	 
	}*/
	
	EditText edit_grpspeed;
	@Override
	void  initialExtraViews(){
		 
	    edit_grpspeed = (EditText)vContainer.findViewById(R.id.act_edit_speed);  
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);  
		   
	}
	@Override
	Group_bean getCurrentGroup(){
		return currentGroup;
	}
	
	
	@Override
	void showWebObject(){
//		  showDetail(svrNumber);
		  if(currentGroup.getId()>0 && currentGroup!=null /*&& currentGroup.getId()==currentGroup.getId()*/){ 
				
//				doWebTrackQuery();//query and show roadbook list
	 
			}else{ //start new action
				newGroup();
			}
			
			getDetails(); 
			
	}
 
	
	@Override
	protected void	initialViews(){
		
		super.initialViews();
	}
  
	 
	  
	void newGroup(){		
		loadLocalGroup();
		if(currentGroup==null||currentGroup.getId()>0){
			currentGroup = new Group_bean();
			currentGroup.setUserId(activity.app.user.getUserbean().getId());
			currentGroup.setUserName(activity.app.user.getUserbean().getUserName());
		}
 	}
 
	void loadLocalGroup(){
		 try {
			currentGroup = getGroupFromWebCache(0,0);
		} catch (JsonSyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	@Override
	void getDetails(){
		
		if(currentGroup.getId()>0  ){
//			act_creator.setText(currentGroup.getUserName());
			setUserLinkSpanTxt(act_creator,currentGroup.getUserId(),currentGroup.getUserName());
			this.BBScate = BBSCate.GROUP.toInt(); // act
			this.BBSSubcate = currentGroup.getId();
			this.BBSsubCateName = currentGroup.getName();
		}else{
			act_creator.setText(activity.app.user.getUserbean().getUserName());
		}
		
	 
		if ( !TextUtils.isEmpty(currentGroup.getAlbum()) ){
			if (currentGroup.getId() > 0){
				IL.DisplayImage(QiYouConstant.BASE_MD_URL +	currentGroup.getAlbum(), this.imgTopBanner);
			}else{
				IL.DisplayImage(currentGroup.getAlbum(), this.imgTopBanner);
			}
		}else {
			 this.imgTopBanner.setBackgroundResource(R.drawable.icon_grpbanner);
		}
		
		
		act_edit_title.setText(currentGroup.getName() );
//		this.edit_act_endGeo.setText(currentGroup.getEndAddress());
//		this.edit_act_startGeo.setText(currentGroup.getStartAddress()); 
		this.edit_act_startGeo.setText(currentGroup.getPlace());
		urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,currentGroup.getGeo().getSharedAddressUrl());
		
		if(currentGroup.getId()>0){
			act_svrNo.setText(currentGroup.getId()+"");
			 
		}
		 
		act_edit_description.setText(currentGroup.getDesc());
//		if(currentGroup.getId()>0)
		act_levlRatingBar.setRating(currentGroup.getLevel());
		
		edit_act_startTime.setText(Utils.getFormatedTime(currentGroup.getCreated())); 
		
		edit_act_distance.setText(String.format("%.1f",currentGroup.getDistance()/1000));  
		//edit_act_distance.setText( Utils.getFormatedDistance(currentGroup.getDistance()) );  
		if(currentGroup.getSportTime()>0){
			float spd =currentGroup.getDistance()/(currentGroup.getSportTime()/1000) *3.6f;
			edit_grpspeed.setText(String.format("%.1f",  spd));
		}
	}
	@Override
	void setDetails(){
		if(currentGroup.getId()==0 || currentGroup.getUserId()<=0){
			currentGroup.setUserId(activity.app.user.getUserbean().getId());				
			currentGroup.setUserName(activity.app.user.getUserbean().getUserName());
			act_creator.setText(currentGroup.getUserName());
		}
//		
		if ( TextUtils.isEmpty(currentGroup.getAlbum()) ){
			IL.DisplayImage(currentGroup.getAlbum(), this.imgTopBanner);
		}else {
			 this.imgTopBanner.setBackgroundResource(R.drawable.icon_banner);
		}
		currentGroup.setName(act_edit_title.getText().toString());
		currentGroup.setDesc(act_edit_description.getText().toString());
//		currentGroup.setRateLevel(act_levlRatingBar.getNumStars());
//		currentGroup.setLevel(act_levlRatingBar.getRating()); 
//  		currentGroup.setPlace(((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).getText().toString());

	}
//	@Override
//	void drawActNaviRoadbook(Track gpxTrack){
//		return;
//	}
	 
 
	@Override
	void validInputs(){
		boolean canEdit = canEdit();
		
//		canEdit=false;
		int visible=canEdit?View.VISIBLE:View.GONE; 
		checkSvrObjUser(currentGroup.getId(),activity.app.user.getUserbean().getId()); 
		 
		 txtStartGeoPicker.setVisibility(visible);  
 		
  		btn_submitAct.setVisibility(visible);		
		btn_submitAct.setEnabled(canEdit);
		btn_saveAct.setEnabled(currentGroup.getId()==0);
		btn_saveAct.setVisibility(currentGroup.getId()==0?View.VISIBLE:View.GONE);	
		btn_submitAct.setText(currentGroup.getId()>0?R.string.act_update:R.string.act_submit);
		
 		act_edit_title.setEnabled(canEdit); 
 		edit_act_startGeo.setEnabled(canEdit);  
		act_edit_description.setEnabled(canEdit);  
 		  
//		  edit_act_distance.setEnabled(canEdit); 
//		  edit_act_speed.setEnabled(canEdit); 

		  		  
		  boolean canJoin = currentGroup.getId()>0;// && currentGroup.getUserId() !=activity.app.user.getUserbean().getId();
		  visible=canJoin ?View.VISIBLE:View.GONE;
		  btn_actJoin.setVisibility(visible);	
		  btn_actJoin.setEnabled(canJoin); 
		  btnShare.setVisibility(visible);
			  
//	      btn_refresh.setEnabled(currentGroup.getId()>0);
//	      btn_refresh.setVisibility(currentGroup.getId()>0?View.VISIBLE:View.GONE);
	}
	@Override
     boolean validSubmit(){ 
		if(currentGroup.getUserId() <=0){
			activity.showLogin();
			return false;
		}
		
		
		if(TextUtils.isEmpty(currentGroup.getName())){
			
//			act_edit_title.setBackgroundColor(Color.YELLOW);
			act_edit_title.setHintTextColor(Color.RED);
			act_edit_title.setSelected(true);
			this.showNotes("请输入队伍名称");
		return false;
		}
		if(currentGroup.getName()!=null && currentGroup.getName() .trim().length()<2){
			
//			act_edit_title.setBackgroundColor(Color.YELLOW);
			act_edit_title.setHintTextColor(Color.RED);
			act_edit_title.setSelected(true);
			this.showNotes("队伍名称太短了");
		return false;
		}

		if( currentGroup.getGeo()==null 
				||  TextUtils.isEmpty(currentGroup.getPlace()) 
//				|| currentGroup.getGeo().getName()==null 
//				|| TextUtils.isEmpty(currentGroup.getGeo().getName().trim())
				
				){
			
//			act_edit_title.setBackgroundColor(Color.YELLOW);
			((EditText) vContainer.findViewById(R.id.act_edit_startGeo)).setHintTextColor(Color.RED);
			this.showNotes("请设置队伍地点");
		return false;
		}
		
		if(TextUtils.isEmpty(currentGroup.getDesc().trim())){
			
//			act_edit_title.setBackgroundColor(Color.YELLOW);
			act_edit_description.setHintTextColor(Color.RED);
			this.showNotes("请输入队伍介绍");
		return false;
		}
		 
		
		
		
		return !TextUtils.isEmpty(currentGroup.getName().trim())
							&& currentGroup.getGeo()!=null
//							&&  currentGroup.getGeo().getName()!=null
//							&& !TextUtils.isEmpty(currentGroup.getGeo().getName().trim())
						    && !TextUtils.isEmpty(currentGroup.getPlace())
							&& !TextUtils.isEmpty(currentGroup.getDesc().trim())
							&& validDate();
		
		
	 
	}
	
	@Override
	 void postSvr() {
			this.postJsonWS(Utils.getGsonString(currentGroup),RestMethods.GRP_P_IMPORT/* "mb/group/"*/);  

	  }
 
	 
	@Override
	void writeLocalObjCache(){
		writeGroupCache(currentGroup);
		showNotes("已保存草稿",false);  
	}
	@Override
	 void joinSvrObj(){
		int userId=activity.app.user.getUserbean().getId();
		int groupId =currentGroup.getId(); 
		String userName=activity.app.user.getUserbean().getUserName();
		String rest =RestMethods.GRP_P_DEL_MEMBER;
	     if(btn_actJoin.getText().toString().equalsIgnoreCase(getResources().getString(R.string.act_join))){
	    	 rest=RestMethods.GRP_P_ADD_MEMBER;
	     }
	    	 			 
	     doMemberOperation(groupId,currentGroup.getName(),currentGroup.getUserId(),userId, userName,rest);

	}
	
	@Override
	void removeUser(int userId){ 
		doMemberOperation(currentGroup.getId(),currentGroup.getName(),currentGroup.getUserId(),userId, "",RestMethods.GRP_P_DEL_MEMBER);
	}
	
	 @Override 
	  void setbackGeoInfo(int textViewId){
		   if(textViewId == R.id.act_txt_startGeo_picker){
	    		activity.latToshow =currentGroup.getLat();
	    		activity.lngToshow =currentGroup.getLon();
	    		
	    	} 
	    	 
	    }
	@Override
	boolean canEdit(){
		return currentGroup.getId()==0
				|| currentGroup==null 
				|| currentGroup.getId()==0
				|| currentGroup.getUserId() ==activity.app.user.getUserbean().getId()
				||this.isAdmin();
	}
	
	@Override
	void setFindResult(){
		if(canEdit() && activity.geoAddress!=null &&activity.geoAddress.getLat()>0 && activity.addressTextId!=0){
			
//			int txtid=activity.addressTextId == R.id.ll_start_place?R.id.act_edit_startGeo
//					:activity.addressTextId == R.id.ll_end_place?R.id.act_edit_endGeo:-1;
			

			int txtid=activity.addressTextId == R.id.act_txt_startGeo_picker?R.id.act_edit_startGeo : -1;
			
			 
			if(txtid==-1)return;
			
			if(activity.geoAddress==null || TextUtils.isEmpty(activity.geoAddress.getCity()) ||TextUtils.isEmpty(activity.geoAddress.getCity().replace("null", "")))return;
			
			EditText text =((EditText)vContainer.findViewById(txtid));
			
			if(text!=null){
				text.setText(activity.geoAddress.getName()); 
				
				if(txtid ==R.id.act_edit_startGeo){
					currentGroup.setGeo(new GEO_bean(activity.geoAddress ));
					currentGroup.getGeo().setSharedAddressUrl(activity.sharedAddressUrl );
//					currentGroup.setStartAddressUrl(activity.sharedAddressUrl);
//					currentGroup.setStartAddress(activity.geoAddress.getAddress());
//					currentGroup.setStartPlace(activity.geoAddress.getName());
//					currentGroup.getGeo().setName(activity.geoAddress.getName());
					currentGroup.setLat(activity.geoAddress.getLat());
					currentGroup.setLon(activity.geoAddress.getLon());
					currentGroup.setPlace(activity.geoAddress.getName() );
					currentGroup.setAddress(activity.geoAddress.getAddress());

					urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,activity.sharedAddressUrl );
				} 
				
					activity.geoAddress=null;
					activity.addressTextId=0;
			}
		}
	}
	 
	 
	@Override
	 void checkSvrObjUser(int groupId,int userId){
		  if(groupId<=0 || userId<=0){
			  return;
		  }
			RequestParams params = new RequestParams();  
			params.add("groupId", String.valueOf( groupId)); 
			params.add("userId", String.valueOf( userId)); 
			//			 QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
			
			getJsonWs(params,RestMethods.GRP_G_IS_MEMBER_HAS_GRP /*"mb/group/isMemberHasGrp"*/,true);
	  }
	 
	
	@Override	
	   void shareEndUrl(int viewId){
			
			Intent sendIntent = new Intent();
			sendIntent.setAction(Intent.ACTION_SEND);
			String url =currentGroup.getGeo().getSharedAddressUrl(); /*viewId==R.id.act_txt_startGeo_share? currentGroup.getStartAddressUrl()
															: currentGroup.getEndAddressUrl();*/
			String title =edit_act_startGeo.getText().toString();//currentGroup.getGeo().getName();
			 title =String.format("【%s】 %s",  currentGroup.getName(),title);
			if(viewId==R.id.act_txt_startGeo_share)
			sendIntent.putExtra(Intent.EXTRA_TEXT, url);
			sendIntent.setType("text/plain");
			startActivity(Intent.createChooser(sendIntent,title ));
			
		}
	
	
	
	
	 
	@Override
	 void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{
		super.processJsonObject(method, jsonObject, msg);
		
		  if(method.equalsIgnoreCase(RestMethods.GRP_P_IMPORT)){ //sumbmit act
			 
			 
			 int svrNo= jsonObject.getInt("id"); 
			 if(svrNo<=0)return;
//			 activity.app.user.getUserbean().setScore(jsonObject.getInt("userScore"));
//			 activity.app.updateUserPref();
			 currentGroup.setLastupdated(jsonObject.getInt("lastupdated"));
			 
			 if(currentGroup.getId()==0){
				 //remove the cache file.
				 delCachedGroup(0,0);
			 }
			 
			 if(currentGroup.getId()!=svrNo){
				
				 currentGroup.setId(svrNo); 
				 
				 doMemberOperation(svrNo,currentGroup.getName(),currentGroup.getUserId(),activity.app.user.getUserbean().getId(),activity.app.user.getUserbean().getUserName(),
						 RestMethods.GRP_P_ADD_MEMBER);   
				
				 if(!TextUtils.isEmpty(currentGroup.getAlbum())){
					 setMD(currentGroup.getAlbum(),0,null,null);
				 }
				 
				 showSubmitedObj(svrNo); 
				 
				 
			 }
			 else{
				  showNotes(msg);  
			 }
			 
			 return;
		  }
	}
	
	 @Override
	  void showGroup(Group_bean group) { 
		 getDetails();  
	  }
	 
	@Override 
	boolean validDate(){
		return true;
	}
	 
	@Override
	 protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){
		 
		 
		IL.DisplayImage(picName,imgTopBanner);
		if (currentGroup.getId()> 0){
			Media md = new Media();
			md.setTrackSvrNumber(currentGroup.getId());
			md.setUri(picName);
			md.setType(mediaType.PIC);
			md.setSvrUri(currentGroup.getAlbum());
			try {
				super.postBinaryWS(md, RestMethods.GRP_P_UPLOAD_ALBUM);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 
			
		}else {
			currentGroup.setAlbum(picName);
		}
		
		 
	 }
	@Override
	 void uploadMediasOnReturn(JSONObject jo)  {
		this.showNotes("图片上传成功！");
		if (jo!=null){
			try {
				if (currentGroup!=null){
					currentGroup.setAlbum(jo.getString("svrUri"));
				} 
				 
				IL.DisplayImage(QiYouConstant.BASE_MD_URL +	jo.getString("svrUri"),imgTopBanner);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	 }
 
	@Override
	public void onResume() { 
//        activity.app.currentGroupiveFragment =TAG;
		super.onResume();
//        activity.updateActionBarTitle(title);	
//        setFindResult();
//        validInputs();
	   
	}
	
}
