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

import java.io.FileNotFoundException;

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

import android.content.Intent;
import android.graphics.Bitmap;
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.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView; 
import com.loopj.android.http.RequestParams;
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.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.User_bean;
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.exception.NoWebObjectException;
import com.qiyou.mb.android.utils.image.QroundimageView;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.utils.Log;

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

	@Override
	public void setFTag() {
		// TODO Auto-generated method stub
		TAG="com.qiyou.UserDetails";
//		FirstTabTextColor= getResources().getColorStateList(R.color.red);    
//		FirstTabBackGround=R.drawable.icon_user;
	}

	public static String getFTag() {
		return "com.qiyou.UserDetails";
		
	}
	
//	public class UserProfile extends TrackList_fragment {
//	protected int currentLayout;
//	int userId;
	private User_bean user;
	private Button btnLogout;
	public static UserDetails newInstance(User_bean user/*,int userId*/)
	{
		
		UserDetails f = new UserDetails(); 
		f.user=user;
	 
	    return f;
	}
	public static UserDetails newInstance()
	{
		
		UserDetails f = new UserDetails(); 
	 
 
	    return f;
	}
	
	
	public void setCurrentUser(User_bean user){
		this.user =user;
	 
//		initialWebQuery();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 super.BBScate = BBSCate.USER.toInt();
	}

	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {   
		 
		vContainer = inflater.inflate(R.layout.user_detail_edit, container, false);
		
		
		initialViews();  
		  title = user.getId()>0 && user.getId()==activity.app.user.getUserbean().getId()?"我的信息"
				  :getResources().getString(R.string.frg_userdetail) +"｜"+user.getUserName()  ;
		return vContainer;
		}		
	
	
	
	 
	
	
 
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState); 
//		  IL = new ImageLoader(activity); 
//		  int actid=-1;
		 
		 
	}
	
 
	 
	
	TextView txtAccount ;
	@Override
	protected void initialViews(){ 
 		super.initialViews();
 		btnLogout =(Button)vContainer.findViewById(R.id.usr_btn_logout); 
 		btnLogout.setOnClickListener(ButtonOnClickListener);
	}
	
	EditText edit_mail; 
	EditText edit_score; 
	QroundimageView imgAbulm;
	@Override
	void  initialExtraViews(){
		txtAccount =(TextView)vContainer.findViewById(R.id.user_account);
		 
		  edit_mail =(EditText)vContainer.findViewById(R.id.user_mailbox);
		  edit_score =(EditText)vContainer.findViewById(R.id.act_edit_score);
		  imgAbulm =(QroundimageView)vContainer.findViewById(R.id.user_abulm); 
		  imgAbulm.setOnClickListener(ButtonOnClickListener);
		  
	}
	
	@Override
	void showWebObject(){
		if(user!=null){
			getDetails();	
		}
			
	}
	
  
	
	
	 
	@Override
	void setDetails(){
		
		if(user==null ||user.getId()==0){
			return;
		}
		/*if(user.getId()!=activity.app.user.getUserbean().getId()){
			return;
		}*/
 //		user.setUserName(txtAccount.getText().toString());
		user.setUserDesc(act_edit_description.getText().toString()); 
		user.setMail(edit_mail.getText().toString());
		 
		int score=user.getScore();
		if(!TextUtils.isEmpty(edit_score.getText().toString())){
			try{
				score =Integer.valueOf(edit_score.getText().toString());
			}catch(Exception e){
				//			 QLog.getLogger().e(dTAG, e.toString());
			}
		}
		user.setScore(score);
		
		if(user.getId()==activity.app.user.getUserbean().getId()){
			user.setQqExprires(QiYouConstant.PV_EXPIRES_IN);
		}else if (!QiYouConstant.DEVELOPER_MODE){
			user.setId(activity.app.user.getUserbean().getId());
		}
	//			 QLog.getLogger().d(dTAG, String.format("user.id %s，activity.app.user.getUserbean().getId() %s",  user.getId(),activity.app.user.getUserbean().getId()));
		
		
		
		

	}
//	@Override
//	void drawActNaviRoadbook(Track gpxTrack){
//		return;
//	}
//	 
 
	@Override
	void getDetails(){
		this.BBScate = BBSCate.USER.toInt(); // act
		this.BBSSubcate = user.getId();
		this.BBSsubCateName = user.getUserName();
		
		txtAccount.setText(user.getUserName());
//		this.edit_act_startGeo.setText(user.getGeo()==null?us);
		if(user.getGeo()!=null){
			urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,user.getGeo().getSharedAddressUrl()); 
			 
				this.edit_act_startGeo.setText(
						(TextUtils.isEmpty(user.getGeo().getCityName())?"":user.getGeo().getCityName())  
						+  
						(TextUtils.isEmpty(user.getGeo().getDistrictName())?"":user.getGeo().getDistrictName())
						
						/*+ user.getGeo().getStreetName()*/);
			
		}
		 
		edit_mail.setText(user.getMail());
		
		act_edit_description.setText(user.getUserDesc());
		
		edit_act_startTime.setText(Utils.getFormatedTime(user.getRegtime())); 
		
//		edit_act_distance.setText(Utils.getFormatedDistance(user.getDistance())); 
		edit_act_distance.setText(String.format("%.1f",  user.getDistance()/1000)); 

 		edit_score.setText(user.getScore()+"");
// 		String imgUrl= TextUtils.isEmpty(user.getAlbum())?user.getQqAbulmUrl() :Utils.getUserAlbum(user.getAlbum());
 		String imgUrl = Utils.getUserAlbum(user);
 		if(!TextUtils.isEmpty(imgUrl)){
 			this.IL.DisplayImage(imgUrl, imgAbulm);	
 		}
 		
 		act_svrNo.setText(user.getId()>0?user.getId()+"":"") ;
 		super.BBSsubCateName  = user.getUserName();
	}
	
 
	
	@Override
	void validInputs(){
		

		/*if(activity.app.user.getUserbean().getId()  <=0){
			activity.showLogin();				
		}*/
		
		boolean canEdit = canEdit() ;//||QiYouConstant.DEVELOPER_MODE;
		int visible=canEdit?View.VISIBLE:View.GONE; 
		txtStartGeoPicker.setVisibility(visible);  
		btn_submitAct.setVisibility(visible);		
		btn_submitAct.setEnabled(canEdit);
//		btn_saveAct.setEnabled(user.getId()==0);
		btn_saveAct.setVisibility(/*user.getId()==0?View.VISIBLE:*/View.GONE);	
		btn_submitAct.setText(/*user.getId()>0?R.string.act_update:*/R.string.act_submit);
		
// 		act_edit_title.setEnabled(/*canEdit*/false); 
 		edit_act_startGeo.setEnabled(canEdit);  
		act_edit_description.setEnabled(canEdit);  
		edit_mail.setEnabled(canEdit &&TextUtils.isEmpty(edit_mail.getText().toString().trim()))  ;
		
//		  edit_act_distance.setEnabled(canEdit); 
//		  edit_act_speed.setEnabled(canEdit); 
  
		
//		  boolean canJoin = activity.user.getId()>0 && activity.user.getUserId() !=activity.app.user.getUserbean().getId();
//		  visible=canJoin ?View.VISIBLE:View.GONE;
		  btn_actJoin.setVisibility(/*visible*/View.GONE);	
//		  btn_actJoin.setEnabled(canJoin);
		  
//	      btn_refresh.setEnabled(true);
//	      btn_refresh.setVisibility(/*activity.user.getId()>0?View.VISIBLE:View.GONE*/View.VISIBLE);
		
	      edit_score.setEnabled(QiYouConstant.DEVELOPER_MODE);
	      super.imgTopBanner.setEnabled(false);
	      imgAbulm.setEnabled(canEdit() || QiYouConstant.DEVELOPER_MODE);
	      
	      btnLogout.setVisibility(canEdit?View.VISIBLE : View.GONE);
		
	}
	
	@Override
    boolean validSubmit(){ 
		
		
		if (!Utils.validate(edit_mail.getText().toString())) {
			this.showNotes( "请输入正确的邮箱", true);
//			Toast.makeText(activity, "请输入正确的邮箱",Toast.LENGTH_LONG).show();
			edit_mail.setHintTextColor(Color.RED);
			edit_mail.setSelected(true);
			return false;
		}
		
		return true;
	}
	
	@Override
	 void postSvr() {
			this.postJsonWS(Utils.getGsonString(user),RestMethods.USER_P_UPDATE/* "mb/group/"*/);  
	  }
	
	 
	
	@Override
	void writeLocalObjCache(){
		 

	}
	@Override
	 void joinSvrObj(){
		 
	
	}
	 @Override 
	  void setbackGeoInfo(int textViewId){
		 if(user.getLat()>0 && user.getLon()>0)
		   if(textViewId == R.id.act_txt_startGeo_picker){
	    		activity.latToshow =user.getLat();
	    		activity.lngToshow =user.getLon();
	    		
	    	} 
	    	 
	    }
	@Override
	boolean canEdit(){
		return user!=null &&
				user.getId() == activity.app.user.getUserbean().getId()
						||this.isAdmin();
	}
	
	@Override
	void setFindResult(){
		int txtid=activity.addressTextId == R.id.act_txt_startGeo_picker?R.id.act_edit_startGeo : -1;
		
		if(activity.geoAddress==null || TextUtils.isEmpty(activity.geoAddress.getCity()) ||TextUtils.isEmpty(activity.geoAddress.getCity().replace("null", "")))return;
		if(txtid==-1)return;
		
		EditText text =((EditText)vContainer.findViewById(txtid));
		
		if(text!=null){
			text.setText(activity.geoAddress.getCity()+activity.geoAddress.getDistrict()); 
			
			if(txtid ==R.id.act_edit_startGeo){
				user.setGeo(new GEO_bean(activity.geoAddress ));
				if(user.getGeo()!=null){
					user.getGeo().setSharedAddressUrl(activity.sharedAddressUrl );
					user.getGeo().setName(activity.geoAddress.getCity() +activity.geoAddress.getDistrict() );
					urlFormat(R.id.act_txt_startGeo_map,R.id.act_txt_startGeo_share,activity.sharedAddressUrl );
				}
				user.setLat(activity.geoAddress.getLat());
				user.setLon(activity.geoAddress.getLon());
			} 
			
				activity.geoAddress=null;
				activity.addressTextId=0;
		}
	 
	}
	
	 
	
	@Override	
	   void shareEndUrl(int viewId){
		
		if(user.getGeo()==null || TextUtils.isEmpty(user.getGeo().getSharedAddressUrl()) ){
			return;
		}
			Intent sendIntent = new Intent();
			sendIntent.setAction(Intent.ACTION_SEND);
			
			String url =user.getGeo().getSharedAddressUrl(); /*viewId==R.id.act_txt_startGeo_share? currentAct.getStartAddressUrl()
															: currentAct.getEndAddressUrl();*/
			String title =edit_act_startGeo.getText().toString();//user.getGeo().getName();
			 title =String.format("【%s】 %s",  user.getUserName(),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 processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException, NullPointerException, NoWebObjectException {  
		 if(method.equalsIgnoreCase(RestMethods.USER_G_FIND_BY_ID)){
 				 user = (User_bean)Utils.getGsonObject(jsonObject.toString(), User_bean.class);
  				 getDetails();	 
			     return;
			}
		 super.processGetJsonObject(method,jsonObject,msg);
		 if(jsonObject==null)return; 
		  
		 
		
	}
	 @Override
	 void processJsonObject(String method,JSONObject jsonObject,String msg)throws JSONException{
		super.processJsonObject(method, jsonObject, msg);
		  if(method.equalsIgnoreCase(RestMethods.USER_P_UPDATE)){ //sumbmit act
			  this.showNotes(msg); 
		  }
		
	 }
	 
	 @Override
	 void showMember(User_bean user){
    	 this.getDetails();
	  }
	 
		@Override
		 protected void setMD(String picName,long time,Waypoint wp,mediaType mdType){
			 
			 
			 
			if (user.getId() > 0){
				Media md = new Media();
				md.setTrackSvrNumber(user.getId());
				md.setUri(picName);
				md.setType(mediaType.PIC);
				md.setSvrUri(user.getAlbum());
			 int tmp = QiYouConstant.WEB_PIC_SIZE;
				try {
					QiYouConstant.WEB_PIC_SIZE = 128;
					super.postBinaryWS(md, RestMethods.USER_P_UPLOAD_ALBUM);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				QiYouConstant.WEB_PIC_SIZE = tmp;
				
			}else {
				user.setAlbum(picName);
			}
			
			 
		 }
		
		@Override
		 void uploadMediasOnReturn(JSONObject jo)  {
			this.showNotes("图片上传成功！");
			if (jo!=null){
				try {
					if (user!=null){
						user.setAlbum(jo.getString("svrUri"));
						if (user.getId() == activity.app.user.getUserbean().getId()){
							activity.app.user.getUserbean().setAlbum(user.getAlbum());
							activity.app.updateUserPref(user);
							
						}
					} 
					 
					IL.DisplayImage(QiYouConstant.BASE_MD_URL +	jo.getString("svrUri"),this.imgAbulm);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		 }
		
		@Override
		void shareObj(){
			    String shareTitle =user.getDistance()> 100 ?  "共运动了"+ edit_act_distance.getText()+"公里" : "和我一起运动吧" ;
				String shareContent =  "约吗？\n" + BBSsubCateName ;
//				Bitmap b = this.imgTopBanner.getDrawingCache();
//				Bitmap b = ((BitmapDrawable)imgTopBanner.getDrawable()).getBitmap();  
				Bitmap b  = Utils.getBitmapFromView(this.imgAbulm);
//				String imgurl = currentAct !=null ? currentAct.getAlbum() :
				 MobclickAgent.onEvent(activity,"shareObj-" + BBSCate.values()[super.BBScate]);
				 QLog.getLogger().d(dTAG, " sharecontent is "+shareContent +",title is "+ title);
				activity.doShare(shareTitle, shareContent, "", b , QiYouConstant.BASE_URL +"list?user=" + user.getId());
				
			
		  }

 
	@Override
	public void onResume() { 
//        activity.app.currentActiveFragment =TAG;
		super.onResume();
//        activity.updateActionBarTitle(title);	
        
	   
	}

}
