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

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

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.Track;
import com.qiyou.mb.android.beans.basic.Activity_bean;
import com.qiyou.mb.android.beans.basic.Group_bean;
import com.qiyou.mb.android.beans.basic.Note;
import com.qiyou.mb.android.beans.basic.NoteMessage;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.User_bean;
import com.qiyou.mb.android.ui.fragments.Querybase_fragment.ListviewOnScroll;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.exception.NoWebObjectException;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;

public class NoteDetail extends NoteList {
	@Override
	public void setFTag() {
		TAG = "com.qiyou.NoteDetail";
	}

	public static String getFTag() {
		return "com.qiyou.NoteDetail";
	}

	@Override
	public String getCurrentTag() {
		return "com.qiyou.NoteDetail";
	}

	public static NoteDetail newInstance(Note note, NoteMessage msg) {
		NoteDetail f = new NoteDetail();
		f.currentNote = note;
		f.currentMsg = msg;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		activity.updateActionBarTitle(R.string.frg_notedetail);

		vContainer = inflater.inflate(R.layout.notes_detail, container, false);
		initialView();
		return vContainer;
	}

	EditText editTitle, editBody;
	TextView viewTitle, viewBody, txtCate, txtSubcate;

	Button btnEdit;

	@Override
	protected void initialView() {
		super.initialView();
		editTitle = (EditText) vContainer.findViewById(R.id.edit_note_title);
		editBody = (EditText) vContainer.findViewById(R.id.edit_note_detail);
 		btnDel = (Button) vContainer.findViewById(R.id.btn_delNote);
		btnEdit = (Button) vContainer.findViewById(R.id.btn_editNote);
		btnEdit.setOnClickListener(ButtonOnClickListener);

		btnDel.setOnClickListener(ButtonOnClickListener);
		viewTitle = (TextView) vContainer.findViewById(R.id.view_note_title);
		viewBody = (TextView) vContainer.findViewById(R.id.view_note_detail);
		txtCate = (TextView) vContainer.findViewById(R.id.txt_note_cate);
		txtSubcate = (TextView) vContainer.findViewById(R.id.txt_note_subcate);

		 lvNotes =(ListView)vContainer.findViewById(R.id.listNotes); 
		 lvNotes.setOnScrollListener(  new ListviewOnScroll());
		 lvNotes.setOnItemClickListener(itemListener);
		 
		// lvNotes.setOnItemClickListener(null);
		// btnSubmit=(Button)vContainer.findViewById(R.id.btn_submitNote);

		/*
		 * btnSubmit.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View view) { try {
		 * Utils.hideSoftKeyboard(activity);
		 * 
		 * submitNote();
		 * 
		 * } catch (JSONException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } catch (UnsupportedEncodingException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); } } });
		 */

	}
	
	
	 OnItemClickListener itemListener = new OnItemClickListener() {  
	        @Override  
	        public void onItemClick(AdapterView<?> parent, View view, int position,  long id) {   
	          QLog.getLogger().d(dTAG, String.format("adapter count %s,postion is %s", parent.getCount(),position));
	        	
	       
	        	if(parent.getCount()==position+1 || !canclick)return;	        	
	        		
	         
	        	canclick =false;  
	        		
	        	lastIndexOnMore =-1;	
//	        	isLoadMoreIndex =false;
	        	selectNotesItem =position; 
	        	if (isNoteQuery) { 
 	        	    showMsgDetail(position) ;
	        		canclick =true;
	        	        return;
	        	  }
	        }
	 };
	 
	 
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		if (currentMsg != null) {
//			setMsgDetail();
//		} else
			setNoteDetail();

//		boolean showDel = this.isAdmin() || getUser().getId() == currentNote.getUserId();
		btnDel.setVisibility(canDelete() ? View.VISIBLE : View.GONE);
		btnEdit.setVisibility(canEdit() ? View.VISIBLE : View.GONE);
		 
	}

	private String cacheKey = "";

	private void setNoteDetail() {
		viewTitle.setVisibility(View.VISIBLE);
		lvNotes.setVisibility(View.VISIBLE);
		btnNew.setVisibility(View.VISIBLE);
		viewTitle.setText(currentNote.getTitle().toString());
		viewBody.setText(currentNote.getBody().toString());
//		this.btnNew.setVisibility(this.currentNote.getStatus()==0 ?View.VISIBLE:View.GONE);		
		this.btnNew.setEnabled(this.currentNote.getStatus()==0);
//		String name =currentNote.getUserName();
//		final int userId = currentNote.getUserId();
		/*
		SpannableString spannableString1 = new SpannableString(name);
		spannableString1.setSpan(new ClickableSpan() {
			@Override
			public void onClick(View view) {
  
				final int cate = BBSCate.USER.toInt();
				cacheKey = cate + "-" + userId;
				String restMethod = "";
				Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey);
 			 
					if (isCached) {
						User_bean obj = (User_bean) activity.app.getWebObjcache()
								.get(cacheKey);
						showMember(obj);

					} else {
						restMethod = RestMethods.USER_G_FIND_BY_ID;
					}
				 

				 if (!TextUtils.isEmpty(restMethod)){
					 RequestParams params = new RequestParams();  
						params.add("id", String.valueOf( userId));		
					       QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
				       getJsonWs(params,restMethod );
				 }
				
 			}
			
		},
		0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		*/
		 
 		TextView txt = (TextView) vContainer.findViewById(R.id.view_note_author); 
 		setUserLinkSpanTxt(txt,currentNote.getUserId(),currentNote.getUserName());
//		txt.setText(  getUserLinkSpanTxt(currentNote.getUserId(),currentNote.getUserName()) );  
//		txt.setMovementMethod(LinkMovementMethod.getInstance());
		
		 com.qiyou.mb.android.utils.image.QroundimageView imgv = 	(( com.qiyou.mb.android.utils.image.QroundimageView) vContainer.findViewById(R.id.msgimgUserAbulm));
		 
		IL.DisplayImage(Utils.getUserAlbum(currentNote.getUserAlbum()), imgv);
		
		((TextView) vContainer.findViewById(R.id.view_note_created))
				.setText(Utils.getFormatedTime(currentNote.getCreated()));

		if (this.BBScate != currentNote.getCategory()
				&& this.BBSSubcate != currentNote.getSubCate()) {
			this.txtCate.setText("["
					+ BBSCate.values()[currentNote.getCategory()].toCHString()
					+ "]");

//			this.txtSubcate.setText("[" + currentNote.getSubCateName()+ "]");

			String text1 = currentNote.getSubCateName() ;
			SpannableString spannableString1 = new SpannableString(text1);
			spannableString1.setSpan(new ClickableSpan() {
				@Override
				public void onClick(View view) {

					if (currentNote.getSubCate() == 0) {
						return;
					}

					final int cate = currentNote.getCategory();
					cacheKey = cate + "-" + currentNote.getSubCate();
					String restMethod = "";
					
					
					
					Boolean isCached = activity.app.getWebObjcache().containsKey(cacheKey);

					if (cate == BBSCate.ACT.toInt()) {
						if (isCached) {
							Activity_bean obj = (Activity_bean) activity.app.getWebObjcache()
									.get(cacheKey);
							showActivity(obj);

						} else {
							restMethod = RestMethods.ACT_G_FIND_BY_ID;
						}
					} else if (cate == BBSCate.GROUP.toInt()) {
						if (isCached) {
							Group_bean obj = (Group_bean) activity.app.getWebObjcache()
									.get(cacheKey);
							showGroup(obj);

						} else {
							restMethod = RestMethods.GRP_G_FIND_BY_ID;
						}
					} else if (cate == BBSCate.USER.toInt()) {
						if (isCached) {
							User_bean obj = (User_bean) activity.app.getWebObjcache()
									.get(cacheKey);
							showMember(obj);

						} else {
							restMethod = RestMethods.USER_G_FIND_BY_ID;
						}
					} else if (cate == BBSCate.TRACK.toInt()) {
						if (isCached) {
							Track obj = (Track) activity.app.getWebObjcache()
									.get(cacheKey);
							showWebTrack(obj);

						} else {
							restMethod = RestMethods.TRACK_G_FIND_BY_ID;
						}
					} else if (cate == BBSCate.GEO.toInt()) {
						activity.showNoteList(cate, currentNote.getSubCate());
					}

					 if (!TextUtils.isEmpty(restMethod)){
						 RequestParams params = new RequestParams();  
							params.add("id", String.valueOf( currentNote.getSubCate()));		
							params.add("swidth", String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH));
							params.add("sheight", String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT));
					       QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
					       getJsonWs(params,restMethod );
					 }
					

				}
			}, 0, text1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			
			txtSubcate.setText(  spannableString1  );
			txtSubcate.setMovementMethod(LinkMovementMethod.getInstance());

		}

	}

	private void setMsgDetail() {

		/*
		viewBody.setText(currentMsg.getBody().toString());
		((TextView) vContainer.findViewById(R.id.view_note_author))
				.setText(currentMsg.getUserName().toString());
		((TextView) vContainer.findViewById(R.id.view_note_created))
				.setText(Utils.getFormatedTime(currentMsg.getCreated()));
 
		lvNotes.setVisibility(View.GONE);
		btnNew.setVisibility(View.GONE);
		viewTitle.setVisibility(View.GONE);
		*/

	}

	@Override
	void editNote() {
		if (canEdit()) {
			activity.showEditNote(currentNote, null);
		}

	}
	
	 
	
	private void editMessage(){
		activity.showEditNote(null, currentMsg);
	}

	@Override
	void doNoteQuery() {
		if (currentNote == null && currentMsg != null) {
			requestNoteFromWeb(currentMsg.getId());
			return;
		}
		Utils.hideSoftKeyboard(activity);

		isNoteQuery = true;
		// lvWeb.setVisibility(View.VISIBLE);
		// lv.setVisibility(View.GONE);
		QLog.getLogger()
				.d(dTAG, TAG + "------begin Note reply query--------- ");

		/*
		 * if( this.firstLoad&&!TextUtils.isEmpty(lastNoteQueryPara)){ return; }
		 */
		RequestParams param = buildNotesQueryParames(0, currentNote.getId());
		if (param != null) {

			QLog.getLogger().d(dTAG, lastNoteQueryPara);
			QLog.getLogger().d(dTAG, param.toString());

			getJsonWs(param, RestMethods.NOTEMSG_G_LIST /* "mb/user/actusers" */);

			selectNotesItem = -1;

		}

	}

	JSONArray msgArray;
	@Override
	void processNotesJsonArray(JSONArray jsonArrary) {
		ArrayList<Map<String, String>> tmpData = new ArrayList<Map<String, String>>();
		JSONObject jo = null;
		NoteMessage ab;
		msgArray = jsonArrary;
		if (jsonArrary != null)
			for (int i = 0; i < jsonArrary.length(); i++) {
				try {
					jo = jsonArrary.getJSONObject(i);
					if (jo == null)
						continue;
					// QLog.getLogger().d(dTAG, "jsonarray:--> "
					// +jo.toString());
					ab = (NoteMessage) Utils.getGsonObject(jo.toString(),
							NoteMessage.class);

				} catch (JsonSyntaxException je) {
					Utils.logStackTrace(je, TAG);
					continue;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Utils.logStackTrace(e, TAG);
					continue;
				}

				if (ab != null) {
					Map<String, String> t = new HashMap<String, String>();
					// t.put("title", ab.getTitle()/*.getAccount()*/);
					t.put("id", String.valueOf(ab.getId()));
					t.put("body", ab.getBody());
					t.put("username", ab.getUserName()+"split%.A.#B&.#C" + ab.getUserId() );
					t.put("created", Utils.getFormatedTime(ab.getCreated()));
					 t.put("album", Utils.getUserAlbum(ab.getUserAlbum()));
					 t.put("userid",  String.valueOf(ab.getUserId()));
					tmpData.add(t);
				}

			}

		noteData = getListData(noteData, tmpData);

		showNoRecText(noteData.size() == 0);

		showNoteData();
		setListViewHeightBasedOnChildren(lvNotes);
		QLog.getLogger().e(
				dTAG,
				String.format("notesPageNo is%s, actual pageno is %s ",
						notesPageNo, noteData.size() / pageSize));

	}

	@Override
	protected void showNoteData() {

		notesSimpleAdapter = new QSimpleAdapter(activity, noteData,
				R.layout.notes_list_detail_msg, new String[] {
				/* "title", */
				"body", "id", "username", "created","album" }, new int[] {
				/* R.id.list_note_name, */
				R.id.list_note_body, R.id.list_note_id,
						R.id.list_note_username, R.id.list_note_created ,R.id.list_note_imgUserAbulm});

	 
		notesSimpleAdapter.setViewBinder( new ViewBinder(){  
	    	 @Override
			public boolean setViewValue(View view, Object data,String textRepresentation) {    		
	    	 	    		 
	    		  switch (view.getId() ){
	    		    
	    			 case R.id.list_note_username:{
	    			 
	    				 
	    				 if(data==null   )return false;
	    			     
	    				 
	    				   String[] res  = data.toString().split("split%.A.#B&.#C");
	    				   
	    				   if (res.length != 2){
	    					   return true;
	    				   }
	    				  
	    				   final int userId = Integer.valueOf(res[1]);
	    				   String name = res[0];
	    				 /*
	    					SpannableString spannableString1 = new SpannableString(name);
	    					spannableString1.setSpan(new ClickableSpan() {
	    						@Override
	    						public void onClick(View view) {

	    							

	    							final int cate = BBSCate.USER.toInt();
	    							cacheKey = cate + "-" + userId;
	    							String restMethod = "";
	    							Boolean isCached = activity.app.getWebObjcache() != null
	    									&& activity.app.getWebObjcache().containsKey(cacheKey);

	    						 
	    								if (isCached) {
	    									User_bean obj = (User_bean) activity.app.getWebObjcache()
	    											.get(cacheKey);
	    									showMember(obj);

	    								} else {
	    									restMethod = RestMethods.USER_G_FIND_BY_ID;
	    								}
	    							 

	    							 if (!TextUtils.isEmpty(restMethod)){
	    								 RequestParams params = new RequestParams();  
	    									params.add("id", String.valueOf( userId));		
 	    							       QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
	    							       getJsonWs(params,restMethod );
	    							 }
	    							

	    						}
	    						
	    					},
	    					0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	    					*/
	    					TextView txt = (TextView)view;
	    					setUserLinkSpanTxt(txt,userId,name);
//	    					txt.setText(  getUserLinkSpanTxt( userId,name) );
//	    					txt.setMovementMethod(LinkMovementMethod.getInstance());
	    				  
 			   	    	  
			   	    	return true;
	    			 }
	    			 case R.id.list_note_imgUserAbulm:{
	    				 com.qiyou.mb.android.utils.image.QroundimageView imgv =  (com.qiyou.mb.android.utils.image.QroundimageView)  view;   
	    				 
	    				 if(data==null   )return false;
	    			      QLog.getLogger().d(dTAG, " displaying available image of " + data.toString());
	    				  IL.DisplayImage( data.toString(),imgv); 
			   	    	  
			   	    	return true;
	    			 }
	    		   
	    		  }
	    		  
	    		  return false;
	    	 }});
		 
		
		bindListView(notesSimpleAdapter, lvNotes, selectNotesItem,
				isNotesLastPage);
		
		 
		
		
		

		lvNotes.setDividerHeight(2);

	}

	@Override
	void requestNoteFromWeb(int noteId) {
		if (noteId <= 0)
			return;
		RequestParams params = new RequestParams();
		params.add("id", String.valueOf(noteId));
		getJsonWs(params, RestMethods.NOTEMSG_G_FIND_BY_ID);
	}

	void showMsgDetail(int position) {
		try {
			
//			HashMap<String, String> localHashMap = (HashMap<String, String>) this.notesSimpleAdapter
//					.getItem(position);
//			noteId = Integer.parseInt(localHashMap.get("id"));
//			int userId = Integer.parseInt(localHashMap.get("userid"));

		
			
			QLog.getLogger().d("com.qiyou",
					TAG + " get selected noteId:" + this.noteId);
			
			currentMsg = (NoteMessage) Utils.getGsonObject(msgArray.get(position).toString(),
					NoteMessage.class);

			if (super.canEdit()){
			
				this.notesSimpleAdapter.setSelectItem(position);
				this.notesSimpleAdapter.notifyDataSetInvalidated();
				this.lvNotes.setSelection(position);
				editMessage();
//				activity.showEditNote(null, currentMsg);
//				activity.showNoteDetail(null, currentMsg);
				
				
				 
	      	}
			

		} catch (NumberFormatException ne) {
			Utils.logStackTrace(ne, TAG);
			showNotes("出错了");
			return;
		} catch (java.lang.IndexOutOfBoundsException IndexException) {
			Utils.logStackTrace(IndexException, TAG);
		} catch (Exception er) {
			Utils.logStackTrace(er, TAG);
		}
		
		

	}

	
	

	@Override
	void processGetJsonObject(String method, JSONObject jsonObject, String msg)
			throws JSONException, NullPointerException, NoWebObjectException {

		super.processGetJsonObject(method, jsonObject, msg);

		if (method.equalsIgnoreCase(RestMethods.NOTEMSG_G_FIND_BY_ID)) {

			// activity.showNoteDetail(null,
			// (NoteMessage)Utils.getGsonObject(jsonObject.toString(),
			// NoteMessage.class));

			currentNote = null;
			currentMsg = (NoteMessage) Utils.getGsonObject(
					jsonObject.toString(), NoteMessage.class);
			setMsgDetail();

		}
	}

	

	@Override
	void showActivity(Activity_bean act) {
		activity.app.getWebObjcache().put(cacheKey, act);
		super.showActivity(act);
	}

	@Override
	void showWebTrack(Track tr) {
		activity.app.getWebObjcache().put(cacheKey, tr);
		super.showWebTrack(tr);
	}

	@Override
	void showGroup(Group_bean group) {
		activity.app.getWebObjcache().put(cacheKey, group);
		super.showGroup(group);
	}

	@Override
	void showMember(User_bean user) {
		activity.app.getWebObjcache().put(cacheKey, user);
		super.showMember(user);
	}
	

		
}
