package com.lianxin.pubqq.main;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.list.utils.NearbyUtil;
import com.lianxin.panqq.main.bean.ListUtil;
import com.lianxin.panqq.main.bean.NearPeople;
import com.lianxin.pubqq.main.adpter.NearbyAdapter;
import com.lianxin.pubqq.main.adpter.NearbyAdapter.OnMyClickListener;
import com.lianxin.pubqq.chat.EMChatActivity;
import com.lianxin.panqq.common.DefineChat;
//import com.lianxin.panqq.chat.entity.EMMessage;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.common.utils.CaptionUtils;
//import com.lianxin.panqq.file.NearbyFileUtil;
import com.lianxin.panqq.main.widght.MyListView;
import com.lianxin.pubqq.nearby.DevicesListActivity;
import com.lianxin.pubqq.nearby.NearbyInfoActivity;
import com.lianxin.pubqq.nearby.NearbySetupActivity;
import com.lianxin.pubqq.nearby.ScanListActivity;
import com.lianxin.pubqq.nearby.WifiListActivity;

public class Fragment_Nearby extends Fragment implements OnClickListener {
	// 局域网用户
	private Activity ctx;
	private View layout;
    private MyListView lvNearby;  
	private NearbyAdapter adpter;    
    private ScrollView qqScroll=null;    
    private float curTouchPosx;
    private float curTouchPosy; 
    private List<NearPeople> nearbys = null; 
	private String  strCaption = "附近,扫描局域网,发现热点,蓝牙连接,附近的我,热点保存,附近的人,接收附近的人"; //服务器各自定制的标题字符串
	private String[]  arrCaption = null; //标题字符串数组   
	private String  strTip = "接收附近的人";	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (layout == null) {
			ctx = this.getActivity();
			layout = ctx.getLayoutInflater().inflate(R.layout.fragment_nearby,
					null);
			initData();	//先要初始化数据，否则下一步出错		
			initViews();
			initCaption();

			setOnListener();
			//initHeartThread();			
		} else {
			ViewGroup parent = (ViewGroup) layout.getParent();
			if (parent != null) {
				parent.removeView(layout);
			}
		}
			
		return layout;
	}

	private void initViews() {
		lvNearby = (MyListView)layout.findViewById(R.id.lvNearby); //实例化expandableLIstView
	      //给adapter设置监听  	
		adpter = new NearbyAdapter(getActivity(),nearbys);
		lvNearby.setAdapter(adpter);		
		ListUtil.setListViewHeightBasedOnChildren(lvNearby);
		adpter.setMyClickListener(new OnMyClickListener(){  
			@Override
			public void onMyClicked(View view, int position) {

				NearPeople user = nearbys.get(position);
				Intent intent = new Intent(getActivity(), EMChatActivity.class);
				intent.putExtra("Chat_ID", user.getSendId());
				//intent.putExtra("Chat_Type", EMMessage.ChatType.ChatType_NEARBY);
				intent.putExtra("Chat_Type", DefineChat.ChatType_USER);				
				intent.putExtra("Chat_Name", user.getName());
				//getActivity().startActivity(intent);
				Utils.start_Activity(getActivity(),intent); 				
			} 
			@Override
			public void onMyClicked1(View view, int position) {
				//Toast.makeText(ctx, "I am " + child.getName(),Toast.LENGTH_SHORT).show();   
				NearPeople user = nearbys.get(position);				
					Intent intent = new Intent(getActivity(), NearbyInfoActivity.class);
					intent.putExtra("Info_UserId", user.getSendId());			
					intent.putExtra("Info_Position", position);
					//getActivity().startActivity(intent);   	
					Utils.start_Activity(getActivity(),intent); 
			}  			
        });
	
		qqScroll = (ScrollView) layout.findViewById(R.id.qq_scroll);
		qqScroll.smoothScrollTo(0, 0);	
	}

	protected void initCaption() {
		//加载服务器定制标题字符串
		//loadCustomCaption();
	    String sCaption = CaptionUtils.LoadCaption( "IDS_NEARBY_WELCOME" );
	    if(!TextUtils.isEmpty(sCaption)&&sCaption.length() > 20)
	        arrCaption = CaptionUtils.SplitCaption( sCaption );	
	    else if(!TextUtils.isEmpty(strCaption)&&strCaption.length() > 20)
	        arrCaption = CaptionUtils.SplitCaption( strCaption );	    
		//如果服务器有自定义字符串    
		if( arrCaption != null && arrCaption.length > 7 ){
			//txt_title.setText(arrCaption[0]);
			((TextView)layout.findViewById(R.id.txt_search)).setText(arrCaption[1]);			
			((TextView)layout.findViewById(R.id.cap_addfriend)).setText(arrCaption[2]);
			((TextView)layout.findViewById(R.id.cap_group)).setText(arrCaption[3]);			
			((TextView)layout.findViewById(R.id.cap_public)).setText(arrCaption[4]);			
			//((TextView)layout.findViewById(R.id.cap_table)).setText(arrCaption[6]);	
			strTip = arrCaption[7];			
		}
	}	
	
	private void setOnListener() {
		// TODO Auto-generated method stub
		layout.findViewById(R.id.layout_addfriend).setOnClickListener(this);
		layout.findViewById(R.id.layout_search).setOnClickListener(this);
		layout.findViewById(R.id.layout_group).setOnClickListener(this);
		layout.findViewById(R.id.layout_public).setOnClickListener(this);
		layout.findViewById(R.id.layout_refresh).setOnClickListener(this);		
	}
	
	private void initHeartThread() {	
	    MyApp.getInstance().startHeartThread();									
	}	
	
	private void initData() {
		if(nearbys != null && nearbys.size() > 0)
			return;	
		List<NearPeople> newNearPeoples = NearbyUtil.initNearbyPeoples(ctx, "area.json");
		GloableParams.NearPeoples = newNearPeoples;	
		nearbys = newNearPeoples;
     
	}

	/**
	 * 刷新页面
	 */
	public void refresh() {
		sortNearPeopleByLastTime(nearbys);		
		adpter.notifyDataSetChanged();		
	}

	public void refreshNewuser() {
		nearbys.clear();
	//	initViews();
		//List<NearPeople> newNearPeoples = NearbyFileUtil.initNearbyPeoples(ctx, "area.json");
		List<NearPeople> newNearPeoples = NearbyUtil.initNearbyPeoples(ctx, "area.json");		
		GloableParams.NearPeoples = newNearPeoples;	
		nearbys = newNearPeoples;		
		sortNearPeopleByLastTime(nearbys);	
	//	updateRecentName();			
		adpter.notifyDataSetChanged();		
	}	

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortNearPeopleByLastTime(
			List<NearPeople> nearuserList) {
		Collections.sort(nearuserList, new Comparator<NearPeople>() {
			@Override
			public int compare(final NearPeople con1,
					final NearPeople con2) {

				if (con2.getOnlineTime() == con1.getOnlineTime()) {
					if (con2.getSendId() > con1.getSendId()) 					
					     return -1;
					else					
					     return 1;					
				} else if (con2.getOnlineTime() > con1.getOnlineTime()) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}	
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();		
		int id = v.getId();
		if (id == R.id.layout_search) {// 搜索好友及公众号
			intent.setClass(getActivity(), ScanListActivity.class);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_addfriend) {
			intent.setClass(getActivity(), WifiListActivity.class);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_group) {
			intent.setClass(getActivity(), DevicesListActivity.class);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_public) {
			intent.setClass(getActivity(), NearbySetupActivity.class);
			//startActivity(intent);
			Utils.start_Activity(getActivity(), intent);
		} else if (id == R.id.layout_refresh) {//Toast.makeText(ctx, "接收附近的人", Toast.LENGTH_SHORT).show();
			Toast.makeText(ctx, strTip, Toast.LENGTH_SHORT).show();
			initHeartThread();
		}
	}

}


