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

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

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.TextUtils;
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.ListView;
import android.widget.AdapterView.OnItemClickListener;

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.Activity_bean;
import com.qiyou.mb.android.beans.basic.Note;
import com.qiyou.mb.android.beans.basic.NoteMessage;
import com.qiyou.mb.android.ui.fragments.Querybase_fragment.ListviewOnScroll;
import com.qiyou.mb.android.utils.ImageLoader;
import com.qiyou.mb.android.utils.QSimpleAdapter;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackStatus;
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 NoteList extends Querybase_fragment {

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

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

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

	public static NoteList newInstance() {
		NoteList f = new NoteList();
		return f;
	}
	public static NoteList newInstance(int cate,int subCate) {
		NoteList f = new NoteList();
		f.BBScate = cate;
		f.BBSSubcate = subCate;
		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_notes);
	 
		vContainer = inflater.inflate(R.layout.notes_list, container, false);
		initialView();
		return vContainer;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		pageSize=20;
//		 doNoteQuery();
	}
	int BBScate = 0;
  	int BBSSubcate = 0; 
  	int BBSSubcateOwner = 0;
  	String BBSsubCateName = "";
  	
 	 NoteMessage currentMsg;
	 Note currentNote;
	 ListView lvNotes =null;
	 int selectNotesItem =0;
	 boolean isNoteQuery  ;
	 String lastNoteQueryPara;
	 int notesPageNo;
	 int noteId;
	 int svrNo;
	 List<Map<String, String>> noteData;
	 Button btnNew	, btnDel; ;//,btnRefresh;
	@Override
	protected void initialView() { 
		 IL = new ImageLoader(activity);
//		 lvNotes =(ListView)vContainer.findViewById(R.id.listNotes); 
//		 lvNotes.setOnScrollListener(  new ListviewOnScroll());
//		 lvNotes.setOnItemClickListener(itemListener);

		 initialLoadingMore();
		 btnNew=(Button)vContainer.findViewById(R.id.btn_newNote);
//		 btnRefresh=(Button)vContainer.findViewById(R.id.btn_refreshNotes);
//		 btnRefresh.setOnClickListener(ButtonOnClickListener);
		 btnNew.setOnClickListener(ButtonOnClickListener);
			
	}

	protected   OnClickListener  ButtonOnClickListener = new OnClickListener() {
		    @Override
			public void onClick(View view) {
		    	switch (view.getId() ){
		    		case R.id.btn_newNote: {postNewNote();break;}	   
//		    		case R.id.btn_refreshNotes: {initialNotesQuery() ;break;}	
		    		case R.id.btn_delNote: {delNote() ;break;}
		    		case R.id.btn_editNote: {editNote() ;break;}

		    	}}};
	 
 
	 void editNote(){}
	 void postNewNote(){
		 activity.showNewNote(currentNote);
	 }
	
	 public void setCurrentMsg(NoteMessage msg){
		  currentMsg=msg; 
		 }
	 public void setCurrentNote(Note note){
		  currentNote=note;
	  }
	  
	  
	 boolean canclick=true;
	    
//	
//	 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) { 
// 	        	    showNoteDetail(position) ;
//	        		canclick =true;
//	        	        return;
//	        	  }
//	        }};
	        	
	  
	  void  doNoteQuery(){
			Utils.hideSoftKeyboard(activity);
		 
			isNoteQuery=true;
//			lvWeb.setVisibility(View.VISIBLE);
//			lv.setVisibility(View.GONE);
			QLog.getLogger().d(dTAG, TAG+"------begin Note query--------- "); 
			
 
		/*	if( 
					this.firstLoad&&!TextUtils.isEmpty(lastNoteQueryPara)){
				return;
			}*/
			RequestParams param=buildNotesQueryParames(0,0);
			if(param!=null  )  {
				
				QLog.getLogger().d(dTAG, lastNoteQueryPara);
				QLog.getLogger().d(dTAG, param.toString());
				
				getJsonWs(param,RestMethods.NOTE_G_LIST /*"mb/user/actusers"*/);
				 
				selectNotesItem =-1;
				
				
			}
			
		}
	
	  RequestParams buildNotesQueryParames(int ownerId,int svrNo){
		  RequestParams params = new RequestParams();
		   
		    params.add("ownerId", String.valueOf(ownerId));
 			params.add("page", String.valueOf(notesPageNo));
			params.add("pagesize", String.valueOf(pageSize));
			params.add("svrNo", String.valueOf( svrNo));	  
			
			
		  return params;
 
		}
	  
	
	  void showNoteDetail(int position){
		  try{
			   this.notesSimpleAdapter.setSelectItem(position);
			   this.notesSimpleAdapter.notifyDataSetInvalidated();
			   this.lvNotes.setSelection(position);
			    HashMap<String, String> localHashMap = (HashMap<String, String>)this.notesSimpleAdapter.getItem(position); 
			    noteId =  Integer.parseInt(localHashMap.get("id")) ;
 
			    QLog.getLogger().d("com.qiyou", TAG + " get selected noteId:" + this.noteId);
			     
		    }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); 
		    }
		   
		  requestNoteFromWeb(noteId);
		  
	  }
	  
	  
		void requestNoteFromWeb(int noteId){
			if(noteId<=0) return;
			RequestParams params =   new RequestParams() ;  
			 params.add("id", String.valueOf(noteId));
			getJsonWs(params, RestMethods.NOTE_G_FIND_BY_ID); 
		}
		
		
		
	  void processNotesJsonArray(JSONArray jsonArrary){
		  ArrayList<Map<String, String>>   tmpData = new ArrayList<Map<String, String>>();
			 JSONObject jo = null;
			 Note ab;
			 
			 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=(Note) Utils.getGsonObject(jo.toString(), Note.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()/*ab.getOwner()!=null?ab.getOwner().getUserName():""*/);
 					 t.put("created", Utils.getFormatedTime(ab.getCreated()));
 					 t.put("replycnt", ab.getReplyCnt() +""); 
 					 t.put("lastreply",ab.getLastupdated() >ab.getCreated() ?ab.getLastReplyer():""); 
 					 
				     tmpData.add(t);
				 }
				  
			 }
			 
			 noteData =  getListData(noteData,tmpData); 
			 
			 showNoRecText(noteData.size()==0);
			 		 
			 showNoteData();
			 
			 QLog.getLogger().e(dTAG, String.format("notesPageNo is%s, actual pageno is %s ",notesPageNo,noteData.size()/pageSize));

		 }
	  
	  QSimpleAdapter   notesSimpleAdapter;
		 
		 int currentUserRow=0;
		protected void showNoteData( ){
		
					notesSimpleAdapter = new QSimpleAdapter(activity,noteData,R.layout.notes_list_detail,
							new String[]{ 
					  				"title",
					  				"body"
					  				 ,"id"
					  				 ,"username" 
					  				 ,"created"
					  				 ,"replycnt"
					  				 ,"lastreply"
									},
							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_reply_cnt
					  				,R.id.list_note_reply_user
	        						}); 
		   
			    
			    bindListView(notesSimpleAdapter,lvNotes,selectNotesItem,isNotesLastPage);
			    
			    lvNotes.setDividerHeight(2);

	  }
		
		
		boolean isNotesLastPage; 


		void processNotesPageInfo(JSONObject jo) throws JSONException{
				 if(jo==null){
					 processGrpJsonArray(null);
					 return;
				 }
				 isNotesLastPage =jo.getBoolean("last");
//			  isGrpFirstPage =jo.getBoolean("first"); 
				    QLog.getLogger().d(dTAG, TAG+"   isNoteLastPage--- " + isNotesLastPage); 

			  processNotesJsonArray(jo.getJSONArray("content"));
		  } 
		
		/*
		 @Override
		 void processGetJsonObject(String method,JSONObject jsonObject,String msg) throws JSONException,NullPointerException, NoWebObjectException {				 
			 
			  super.processGetJsonObject(method, jsonObject, msg);
			  
			 if(method.equalsIgnoreCase(RestMethods.NOTE_G_LIST) ||method.equalsIgnoreCase(RestMethods.NOTEMSG_G_LIST)  ) {
				 
				 if(checkJsonArray(jsonObject)){
					   
					 
					 QLog.getLogger().d(dTAG, TAG+"------get notes web query data--------- "); 
 				 	 QLog.getLogger().d(dTAG, TAG+" notes : "+jsonObject.toString());
 				 	 
 				 	 processNotesPageInfo(jsonObject ); 

					}
					
		      }else if(method.equalsIgnoreCase(RestMethods.NOTE_G_FIND_BY_ID)  ) {
		    	   
		    	  activity.showNoteDetail( (Note)Utils.getGsonObject(jsonObject.toString(), Note.class),null);
		    	  
			  }
			  
		 }
		 */
		 
		  @Override
			void loadingMore(){ 
		      
				 QLog.getLogger().d(dTAG, "------ can loading more 2  .. " + canLoadingMore);

				isLoadingMore =true;
//					isLoadMoreIndex=true;
				lastIndexOnMore =visibleLastIndex;
		    	  if(isNoteQuery){
//		 			lastGrpQueryPara="";
		    		 notesPageNo++;
		     		 doNoteQuery();
				}
				
				 
				
			}  
		
		void initialNotesQuery(){
			notesPageNo=1;
		    doNoteQuery();
		}
		   
		  
	 @Override
	 public void onResume() {
		
		 initialNotesQuery(); 
	   	super.onResume(); 
	}
	 
	 
    
    @Override
	public boolean isShowBottomTabs() {
		// TODO Auto-generated method stub
		return false;
	}

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

	}
 
	@Override
	public void doQuery() {
		// TODO Auto-generated method stub
		 this.initialNotesQuery();
	}
	
 	void delNote() {

//		if (canDelete()) {

			final JSONObject json = new JSONObject();

			int id = currentNote == null ? currentMsg.getId() : currentNote
					.getId();
			final String method = currentNote == null ? RestMethods.NOTEMSG_P_DEL
					: RestMethods.NOTE_P_DEL;
			try {
				json.put("noteId", id);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
			AlertDialog.Builder builder = new Builder(activity);
			   builder.setMessage("确认删除吗？");
			   builder.setTitle("提示");
			   builder.setCancelable(false);
			   builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
				   @Override
				   public void onClick(DialogInterface dialog, int which) {
				   dialog.dismiss();	
				 
					  
			            postJsonWS(json.toString(), method);
						 
				   
					}
				});
			  builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
				 @Override
				 public void onClick(DialogInterface dialog, int which) {
					 dialog.dismiss();
					 
					 }
				 });
			  	builder.create().show();
			
			 
			 
//		}

 	}
	@Override
	void processJsonObject(String method, JSONObject response, String msg)
			throws JSONException {

		/*
		 * QLog.getLogger().d(dTAG,"发布成功！" ); QLog.getLogger().d(dTAG,
		 * response.toString() ); Toast.makeText(activity, "删除成功！",
		 * Toast.LENGTH_LONG).show();
		 */

		this.showNotes(msg);
		if (method.equalsIgnoreCase(RestMethods.NOTE_P_DEL)
				|| method.equalsIgnoreCase(RestMethods.NOTEMSG_P_DEL)) { // LEAVE
																			// activity,group
			if (Boolean.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))) {
				// success
				 activity.isNeedFresh=true;
				onBack();

			}
		}
//		btnSubmit.setEnabled(true);
		 
		else if(method.equalsIgnoreCase(RestMethods.NOTE_P_IMPORT) || method.equalsIgnoreCase(RestMethods.NOTEMSG_P_IMPORT) ) { //LEAVE activity,group
			 if(Boolean.valueOf(response.getString(QiYouConstant.SIMPLE_KEY))){
					
				 activity.isNeedFresh=true;
				 onBack();  //success
					  
			 }   
		 }

	}
	
	boolean canDelete(){
		return (this.currentNote != null && (currentNote.getUserId() == this
				.getUser().getId() || isAdmin()))
				|| (this.currentMsg != null && (currentMsg.getUserId() == this
						.getUser().getId()
				 || isAdmin()))
				 ||  this.currentNote != null && (currentNote.getCateOwnerId() == this
								.getUser().getId());
	}
	boolean canEdit() {
		return canDelete() ;
	}
	
}
