package com.lianxin.pubqq.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import com.lianxin.pubqq.R;
import com.lianxin.pubqq.activity.adpter.GroupListAdapter;
import com.lianxin.pubqq.activity.adpter.GroupListAdapter.OnMyButClickListener;
import com.lianxin.panqq.edit.AskJoinDialog;
import com.lianxin.panqq.common.BaseActivity;
import com.lianxin.panqq.common.DefineUser;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.widget.list.XListView;
import com.lianxin.panqq.widget.list.XListView.IXListViewListener;
import com.lianxin.panqq.main.EMGroupManager;
//import com.lianxin.panqq.chat.utils.MyLogger;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.list.bean.GroupNode;
import com.lianxin.panqq.list.utils.FriendUtils;
import com.lianxin.panqq.client.AskClient;
import com.lianxin.panqq.client.adminGroupClient;
import com.lianxin.panqq.client.callback.askCallBack;
import com.lianxin.panqq.client.callback.updataCallBack;
import com.lianxin.panqq.client.entity.AdminGroupFor;
import com.lianxin.panqq.client.entity.AdminGroupList;
import com.lianxin.panqq.common.bean.AskInfo;

//群组管理界面
public class AdminGroupActivity extends BaseActivity implements OnClickListener,IXListViewListener {
	private ImageView img_back, img_right;    
	private XListView mListView;
	private GroupListAdapter mAdapter;
	private List<GroupNode> groupList;//搜索用户列表
	private int groupType = DefineUser.TYPE_CROWD;	
	AdminGroupFor groupFor;	
	public static final int FRIST_GET_DATE = 111;
	public static final int REFRESH_GET_DATE = 112;
	public static final int LOADMORE_GET_DATE = 113;
	
	private static int page = 0;

	//private static MyLogger Log = MyLogger.yLog();
	
    @Override
   	public void onCreate(Bundle savedInstanceState) {
      	 
   		super.onCreate(savedInstanceState);
   		setContentView(R.layout.activity_grouplist);
		img_back = (ImageView) findViewById(R.id.img_back);
		img_right = (ImageView) findViewById(R.id.img_right);   		
		img_back.setOnClickListener(this);
		img_right.setOnClickListener(this);  		
		mListView = (XListView)findViewById(R.id.group_xListView);
		mListView.setPullLoadEnable(true);
		groupType = getIntent().getIntExtra("Info_GroupType", 3);
		
		initData();
		 
		mAdapter =  new GroupListAdapter(this, groupList);
		mListView.setAdapter(mAdapter);
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {
	            Toast.makeText(context, "I am ", Toast.LENGTH_SHORT).show(); 				
				Intent intent = new Intent(AdminGroupActivity.this, GroupInfoActivity.class);				
				GroupNode groupInfo = mAdapter.getItem(position-1);	
				intent.putExtra("Info_GroupId", groupInfo.classId);
				intent.putExtra("Info_GroupName", groupInfo.classname);
				intent.putExtra("Info_GroupType", groupType);				
				intent.putExtra("Info_Type", groupInfo.keyword);
				intent.putExtra("Info_Enyear", groupInfo.address);
				intent.putExtra("Info_Number", groupInfo.number);
				intent.putExtra("Info_Open", groupInfo.maxcount);					
				startActivity(intent);			}
			
		});
		
		mAdapter.setButListener(new OnMyButClickListener(){  
			@Override
			public void onButClicked(int position) {
				// TODO Auto-generated method stub
				onItemButtonClick(position);						
			}  
        });	
		resetData();	//刷新远程数据		
    }
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.img_back) {
			Utils.finish(AdminGroupActivity.this);
			//finish();
		} else if (id == R.id.img_right) {
			Intent intent = new Intent();
			intent.setClass(this, UserSearchActivity.class);
			intent.putExtra("REQUEST_FROM", 1);
			startActivityForResult(intent, 20);
		}
	} 
	
	public void onItemButtonClick(int position) {
		// TODO Auto-generated method stub
		GroupNode groupInfo = mAdapter.getItem(position);
		int nGroupId = groupInfo.getClassId();
		String strGroupName = groupInfo.getName();			
		int image = groupInfo.imageid;		
		AskInfo uinfo = new AskInfo(nGroupId,strGroupName,image);			
		new AskJoinDialog(AdminGroupActivity.this,uinfo,
				new AskJoinDialog.OnSetListener() {
					@Override
					public void onSelect(AskInfo askInfo) {
						joinGroup(askInfo);
					}
				}).show();
    }	
	
    //第一次加载数据
    private void initData() {
		if(groupList != null && groupList.size() > 0)
			return;    	
    	mListView.setPullLoadEnable(false);
 		mListView.setPullRefreshEnable(false);
 		 
      //  if(TextUtils.isEmpty(GloableParams.m_szServerIp))         	
 		    LoadLocalItems(FRIST_GET_DATE); 
       // else
 		//    getRemoteItems(FRIST_GET_DATE);
	}
    //刷新远程数据
    private void resetData() {
   	    mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(false);
		 
        if(TextUtils.isEmpty(GloableParams.m_szServerIp))         	
		    LoadLocalItems(REFRESH_GET_DATE); 
        else
		    getRemoteItems(REFRESH_GET_DATE);
	}  

	@Override
	public void onRefresh() { 
		mListView.setPullLoadEnable(false);
		 mListView.setPullRefreshEnable(false);
        if(TextUtils.isEmpty(GloableParams.m_szServerIp))         	
 		    LoadLocalItems(REFRESH_GET_DATE); 
        else
 		    getRemoteItems(REFRESH_GET_DATE);	    
	}
 
	@SuppressLint("SimpleDateFormat")
	private void onLoadStatus(int allCount,int newCount) {
		// TODO Auto-generated method stub
		mListView.stopRefresh();
		mListView.stopLoadMore();
		if(newCount>=0){
		    SimpleDateFormat  formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");     
		    Date  curDate  =  new Date(System.currentTimeMillis());//获取当前时间     
		    String   str   =   formatter.format(curDate);     
		    mListView.setRefreshTime(str);
		    mListView.setFooterCount(allCount, newCount);	
		}
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
	}	
	
	@Override
	public void onLoadMore() { 
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(false);
	
        if(TextUtils.isEmpty(GloableParams.m_szServerIp)) 		 
 		    LoadLocalItems(REFRESH_GET_DATE); 
        else
 		    getRemoteItems(REFRESH_GET_DATE);  		
	}

	private void getRemoteItems(final int ACTION) {
		adminGroupClient.searGroup(ACTION, new updataCallBack(){		
			@Override
			public void onSuccess(int statusCode, byte[] recvBuf) {
				AdminGroupList searlist = new AdminGroupList(recvBuf);	
				final List<GroupNode> newgroupList = searlist.getGroupList();	
				runOnUiThread(new Runnable() {
					public void run() {
						int newCount = 0;
						if(newgroupList == null )
							newCount = 0;
						else
							newCount = newgroupList.size();	
						if(ACTION==REFRESH_GET_DATE||ACTION==FRIST_GET_DATE){
							groupList = newgroupList;					
						}
						else
						{		
							if(newgroupList != null )
							for(int i=0;i<newgroupList.size();i++){ 
								
								groupList.add(newgroupList.get(i));			
							}
						}
					//	Toast.makeText(GroupListActivity.this, "message"+statusCode, 0).show();				
						int allCount = groupList.size();		
						if(ACTION==FRIST_GET_DATE){//第一次加载
							onLoadStatus(allCount,newCount);
							page = 1;						
						}else if(ACTION==REFRESH_GET_DATE){//刷新数据
							mAdapter = new GroupListAdapter(AdminGroupActivity.this, groupList);
							mListView.setAdapter(mAdapter);
							mAdapter.setButListener(new OnMyButClickListener(){  
								@Override
								public void onButClicked(int position) {
									// TODO Auto-generated method stub
									onItemButtonClick(position);						
								}  
					        });							
							onLoadStatus(allCount,newCount);
							page = 1;
						}else if(ACTION==LOADMORE_GET_DATE){//加载更多
							mAdapter.notifyDataSetChanged();
							onLoadStatus(allCount,newCount);
							page++; 
						}								
					}
				});					
				
			}

			@Override
			public void onFailure(int statusCode,  String message) {
				final String str = message;				
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(AdminGroupActivity.this, str, 0).show();						
						onLoadStatus(0,-1);								
					}
				});	
				return;
			}

			
		});
	 
	}	
	
	private void LoadLocalItems(final int ACTION) {

		int newCount = 0;
		List<GroupNode> newgroupList = null;	
		if(ACTION==REFRESH_GET_DATE||ACTION==FRIST_GET_DATE){
			newgroupList = EMGroupManager.getInstance().loadGroup(groupType);			
		//	userList.clear();
			groupList = newgroupList;
			if(newgroupList == null )
				newCount = 0;
			else
				newCount = newgroupList.size();				
		}
		else
		{
			newgroupList = EMGroupManager.getInstance().loadGroup(groupType);
			if(newgroupList == null )
				newCount = 0;
			else
				newCount = newgroupList.size();			
			if(newgroupList != null )
			for(int i=0;i<newgroupList.size();i++){ 
				
				groupList.add(newgroupList.get(i));			
			}
		}
		int allCount = groupList.size();		
			if(ACTION==FRIST_GET_DATE){//第一次加载
				onLoadStatus(allCount,newCount);
				page = 1;			
			}else if(ACTION==REFRESH_GET_DATE){//刷新数据
				mAdapter = new GroupListAdapter(AdminGroupActivity.this, groupList);
				mListView.setAdapter(mAdapter);
				mAdapter.setButListener(new OnMyButClickListener(){  
					@Override
					public void onButClicked(int position) {
						// TODO Auto-generated method stub
						onItemButtonClick(position);						
					}  
		        });				
				onLoadStatus(allCount,newCount);
				page = 1;
			}else if(ACTION==LOADMORE_GET_DATE){//加载更多
				mAdapter.notifyDataSetChanged();
				onLoadStatus(allCount,newCount);
				page++; 
			}		

	}	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) { // 清空消息
			//Intent intent = new Intent();			
			switch (requestCode) {
			case 20:
				onRefresh();
				break;			
			default:
				break;
			}			
		}
	}	

	public void joinGroup(AskInfo uinfo){
		int nDestid = uinfo.destid;
		if(nDestid == GloableParams.m_szUserId){//判断是否是自己
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "不能添加自己"));
		//	return;
		}	
		if(FriendUtils.getFriendList(nDestid)>0){//判断是否已经是好友
		//	startActivity(new Intent(this, AlertDialog.class).putExtra("msg", "此用户已是你的好友"));
		//	return;
		}		
		getLoadingDialog("正在发送请求...").show();		
		AskClient.AskJoinGroup(groupType,uinfo,new askCallBack(){	
			@Override
			public void onSuccess(int statusCode, String message) {
				getLoadingDialog("正在发送请求...").dismiss();	
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(AdminGroupActivity.this, str);
					}
				});				
			}
			@Override
			public void onFailure(int statusCode,  String message) {
				getLoadingDialog("正在发送请求...").dismiss();
				final String str = message;
				runOnUiThread(new Runnable() {
					public void run() {
						Utils.showLongToast(AdminGroupActivity.this, str);
					}
				});	
			}
		});	 
	}	
	
}
 