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.AdapterView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.main.bean.ListUtil;
import com.lianxin.panqq.main.bean.LivePerson;
import com.lianxin.panqq.chat.EMLiveManager;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.common.utils.CaptionUtils;
import com.lianxin.pubqq.ulive.adpter.LiveLocalAdapter;
import com.lianxin.panqq.main.widght.MyListView;
import com.lianxin.pubqq.ulive.LearnWatchActivity;
import com.lianxin.pubqq.ulive.LivePublishActivity;
import com.lianxin.pubqq.ulive.LiveWatchActivity;
import com.lianxin.pubqq.ulive.LivesListActivity;

public class Fragment_Live extends Fragment implements OnClickListener {
	// 用户直播或者教学
	private Activity ctx;
	private View layout;
    private MyListView listView;  
	private LiveLocalAdapter adpter;    
    private ScrollView qqScroll=null;    
    private float curTouchPosx;
    private float curTouchPosy; 
    private List<LivePerson> livelist = 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_live,
					null);
			initData();	//先要初始化数据，否则下一步出错		
			initViews();
			initCaption();

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

	private void initViews() {

		listView = (MyListView)layout.findViewById(R.id.lvLiveList); //实例化expandableLIstView

		adpter = new LiveLocalAdapter(getActivity(),livelist);		
		listView.setAdapter(adpter);
		adpter.setListView(listView);		
		ListUtil.setListViewHeightBasedOnChildren(listView);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position,
					long id) {	
				LivePerson person = livelist.get(position);				
				Intent intent = new Intent(getActivity(), LiveWatchActivity.class);	
				//Intent intent = new Intent(getActivity(), LearnWatchActivity.class);				
				intent.putExtra("Publishid", person.getSendId());
				intent.putExtra("Watchid", person.getRecvId());	
				intent.putExtra("RoomName", person.getRoomName());				
				//startActivity(intent);
				Utils.start_Activity(getActivity(),intent);				
				}		
		});
		EMLiveManager.isLocalBroadListen = true;
		qqScroll = (ScrollView) layout.findViewById(R.id.qq_scroll);
		qqScroll.smoothScrollTo(0, 0);	
	}

	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);
	}
	
	private void initHeartThread() {	
								
 
	}	
	
	private void initData() {
		if(livelist != null && livelist.size() > 0)
			return;	
		livelist = GloableParams.LivePersons;
		if(livelist != null && livelist.size() > 0)
			return;			
    	    LivePerson newPerson = new LivePerson();
	 	    newPerson.sendid = 1000;
	        newPerson.setNickName("strName"); 
	        newPerson.setRoomName("strName");     	        
	        newPerson.setImagePos(24);
	        newPerson.setIp("strIp");     	        
	        
	        GloableParams.LivePersons.add(newPerson);  
	    livelist = GloableParams.LivePersons;	      
	}

	protected void initCaption() {
		//加载服务器定制标题字符串
		//loadCustomCaption();
	    String sCaption = CaptionUtils.LoadCaption( "IDS_LIVE_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];			
		}
	}	
	
	/**
	 * 刷新页面
	 */
	public void refresh() {
	//	recentList.clear();
	//	initViews();
		sortLivePersonByLastTime(livelist);		
		adpter.notifyDataSetChanged();		
	}

	public void updateItemData( int userid ) {
		
		//adpter.updateItemData(userid,null);	
		adpter.updateItemThumb( userid );
		
	}	
	
	public void refreshNewuser() {
		livelist.clear();
	//	initViews();
		List<LivePerson> newLivePersons = null;
		GloableParams.LivePersons = newLivePersons;	
		livelist = newLivePersons;		
		sortLivePersonByLastTime(livelist);	
	//	updateRecentName();			
		adpter.notifyDataSetChanged();		
	}	

	/**
	 * 根据最后一条消息的时间排序
	 * 
	 * @param usernames
	 */
	private void sortLivePersonByLastTime(
			List<LivePerson> nearuserList) {
		Collections.sort(nearuserList, new Comparator<LivePerson>() {
			@Override
			public int compare(final LivePerson con1,
					final LivePerson 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;
				}
			}

		});
	}	

	private void updateItemThumb( int userid ) {
		int targetIndex = -1;
	    for(int i=0;i<livelist.size();i++)
	    {
	    	if(livelist.get(i).sendid == userid ){
	    		targetIndex = i;	    		
	    		break;
	    	}        
	    }		
		int startShowIndex = listView.getFirstVisiblePosition();
		int endShowIndex = listView.getLastVisiblePosition();
        if (targetIndex >= listView.getFirstVisiblePosition() && targetIndex <= listView.getLastVisiblePosition())  
        {  
            View view = listView.getChildAt(targetIndex - startShowIndex);
            //ImageView imageView = (ImageView) view.findViewById(R.id.img_item_gridview);
    		//imageView.setImageBitmap(bitmap);  
    		adpter.getView(targetIndex, view, listView);   		
        }		
	}	
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent();		
		switch (v.getId()) {
		case R.id.layout_search:// 搜索好友及公众号
			intent.setClass(getActivity(), LivesListActivity.class);	
			//intent.putExtra("REQUEST_FROM", 0);	
			//intent.putExtra("SEARCH_TYPE", DefineUser.TYPE_CROWD);				
		    //startActivity(intent);	
			startActivityForResult(intent, 20);			    
			break;		
		case R.id.layout_addfriend:		 
            //startActivity(new Intent(getActivity(), LearnWatchActivity.class));
            intent.setClass(getActivity(), LearnWatchActivity.class); 
            Utils.start_Activity(getActivity(),intent);            
			break;
		case R.id.layout_group:// 群聊
            //startActivity(new Intent(getActivity(), LiveWatchActivity.class));  
            intent.setClass(getActivity(), LiveWatchActivity.class);
            Utils.start_Activity(getActivity(),intent);           
			break;
		case R.id.layout_public:// 公众号  
            //startActivity(new Intent(getActivity(), LivePublishActivity.class));
            intent.setClass(getActivity(), LivePublishActivity.class); 
            Utils.start_Activity(getActivity(),intent);           
			break;
		default:
			break;
		}
	}

}


