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

import java.util.ArrayList;
import java.util.Map;

import org.json.JSONArray;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
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.utils.Utils;
import com.qiyou.mb.android.utils.enums.BBSCate;
import com.qiyou.mb.android.utils.enums.WebQueryCate;
import com.qiyou.mb.android.utils.server.RestMethods;

public class ActivityHome extends ActivityDetail {

	@Override
	public String getCurrentTag() {
		// TODO Auto-generated method stub
		setFTag();
		return TAG;
	}

	@Override
	public void setFTag() {
		// TODO Auto-generated method stub
		TAG = "com.qiyou.ActivityHome";
		// FirstTabTextColor= getResources().getColorStateList(R.color.red);
		// FirstTabBackGround=R.drawable.icon_star;
	}

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

	public static ActivityHome newInstance(Activity_bean activity/*
																 * int
																 * inType,int
																 * actId
																 */) {

		ActivityHome f = new ActivityHome();
		f.currentAct = activity;
		/*
		 * Bundle args = new Bundle(); args.putInt(QiYouConstant.EXTRA_KEY_ID,
		 * actId); f.setArguments(args);
		 */
		return f;
	}

	public static ActivityHome newInstance() {

		ActivityHome f = new ActivityHome();

		return f;
	}

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

		if (currentAct == null) {

			currentAct = new Activity_bean();

		}
		// svrNumber =currentAct.getSvrNumber();

		title = currentAct.getSvrNumber() > 0 ? 
//				getResources().getString(R.string.bottom_web)+ "》"+
				 getResources().getString(R.string.frg_actdetail)
				+ "｜"
				+ currentAct.getName() : getResources().getString(
				R.string.frg_actnew);

		currentLayout = R.layout.activity_home;
		vContainer = inflater.inflate(currentLayout, container, false);

		webTab = "活动";
		initialViews();
		// initialLLViews();
		// initialMapview();

		return vContainer;
	}

	private LinearLayout roadBookbar;
	private TextView actTitle, actLevel, actTime, actAvs, actDist;
	protected Button btnHeadDetail;

	@Override
	protected void initialViews() {
		// android:id="@+id/actList_level" android:id="@+id/actList_avs"
		// android:id="@+id/actList_sportTime" android:id="@+id/"
		// android:id="@+id/actList_svrNo" android:id="@+id/actList_name"
		txtNote = (TextView) vContainer.findViewById(R.id.txtNotice);
		btnHeadDetail = (Button) vContainer.findViewById(R.id.btnHeadDetail);
		btnHeadDetail.setOnClickListener(super.ButtonOnClickListener);

		initialExtraViews();

//		imgWebPlus = (ImageView) vContainer.findViewById(R.id.img_webAdd);
//		imgWebPlus.setOnClickListener(ButtonOnClickListener);
//		imgWebPlus.setVisibility(View.GONE);
		initialTabhost();

		bbsbar = (LinearLayout) vContainer.findViewById(R.id.bbsBar);

		liveMap = (LinearLayout) vContainer.findViewById(R.id.liveMap);
		liveList = (LinearLayout) vContainer.findViewById(R.id.ll_liveList);
		liveList.setVisibility(View.VISIBLE);
		lvWeb = (ListView) vContainer.findViewById(R.id.tr_listWeb);// .act_member_list);
		lvWeb.setOnItemClickListener(itemListener);
		// lvWeb.setOnTouchListener(new OnTouchListener() {
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// Utils.hideSoftKeyboard(activity);
		// return false;
		// }
		// });
		initialMapview();
		initialLoadingMore();

	}
	
	@Override
	void hideNotes(){}

	// initial act summary,roadbookbar,etc,need to be overrided
	@Override
	void initialExtraViews() {

		act_svrNo = (TextView) vContainer.findViewById(R.id.actList_svrNo);

		// act_roadbook = (EditText)
		// vContainer.findViewById(R.id.act_edit_roadbook);
		actTitle = (TextView) vContainer.findViewById(R.id.actList_name);
		actLevel = (TextView) vContainer.findViewById(R.id.actList_level);
		;
		actAvs = (TextView) vContainer.findViewById(R.id.actList_avs);
		;
		actTime = (TextView) vContainer.findViewById(R.id.actList_sportTime);
		;
		actDist = (TextView) vContainer.findViewById(R.id.actList_dist);
		;

		// noRec = (TextView) vContainer.findViewById(R.id.trakList_tv_norec);
		

		roadBookbar = ((LinearLayout) vContainer.findViewById(R.id.roadBookbar));
		initialRoadBookViews();
	}

	private void initialRoadBookViews() {
		boolean canEdit = canEdit();

		btn_loadRoadbook = (Button) vContainer
				.findViewById(R.id.act_btn_loadRoadbook);
		btn_loadRoadbook.setOnClickListener(ButtonOnClickListener);

		lvWeb = (ListView) vContainer.findViewById(R.id.tr_listWeb);
		// lvWeb =(SwipeListView)vContainer.findViewById(R.id.tr_listWeb);

		act_roadbook = (EditText) vContainer
				.findViewById(R.id.act_edit_roadbook);

		roadbookRdGroup = (RadioGroup) vContainer
				.findViewById(R.id.act_rdGroup_rooadbook);
		if (roadbookRdGroup != null)
			roadbookRdGroup.setOnCheckedChangeListener(rdgChanged);

		btn_loadRoadbook.setEnabled(canEdit);
		act_roadbook.setEnabled(canEdit);
		this.roadbookRdGroup.setEnabled(canEdit);
		for (int i = 0; i < roadbookRdGroup.getChildCount(); i++) {
			roadbookRdGroup.getChildAt(i).setEnabled(canEdit);
		}


	}

	@Override
	void showObjDetail() {
		activity.showActvity(currentAct);
	}

	@Override
	void showWebObject() {
		showDetail(currentAct.getSvrNumber());
	}

	private void showDetail(int actid) {
		if (actid > 0 && currentAct != null
				&& actid == currentAct.getSvrNumber()) {
			
			if(currentAct.getRoadbooks().size()>0){
//				doWebTrackQuery();//query and .show roadbook list
			}

			getDetails();
		}

	}

	@Override
	void addTabs() {
		tabBbs = tabhost.newTabSpec(bbsTab);
		tabBbs.setIndicator(bbsTab);
		tabBbs.setContent(tabResourceId);

		tabhost.addTab(tabBbs);
		tabhost.addTab(tabRoadbook);
		tabhost.addTab(tabUser);
		tabhost.addTab(tabTrack);
		tabhost.addTab(tabLive);

	}

	@Override
	void refresh() {

		// if(currentTab==0){
		// requestActFromWeb( currentAct.getSvrNumber());
		//
		// }else
		if (isWebTrackQuery) { // show road book

			this.initialWebQuery();
		} else if (isActivityQuery) {

			this.initialWebQuery();

		} else if (isLiveQuery) {
			showLive();

		} else if (isMemberQuery) {
			this.initialWebQuery();

		} else if (this.isShareQuery) {
			if (currentAct == null || currentAct.getSvrNumber() == 0)
				return;
			this.initialWebQuery();
		}

	}

	@Override
	void getDetails() {

		this.BBScate = BBSCate.ACT.toInt(); // act
		this.BBSSubcate = currentAct.getSvrNumber();
		this.BBSsubCateName = currentAct.getName();
		 BBSSubcateOwner = currentAct.getUserId();

		actTitle.setText(currentAct.getName());
		actLevel.setText(String.format("%.0f", currentAct.getRateLevel()));
		actAvs.setText(String.format("%.0f", currentAct.getAvSpeed()));
		actDist.setText(String.format("%.0f", currentAct.getDistance()));
		actTime.setText(currentAct.getAvSpeed() > 0 ? String.format("%.0f",
				currentAct.getDistance() / currentAct.getAvSpeed()) : "--");
//		act_svrNo.setText(currentAct.getSvrNumber() + "");
		act_svrNo.setText(String.format("距你  %s ， %s",Utils.getDistanceRange(/*ab.getDistrange()*/0, currentAct.getLat(), currentAct.getLon()) 
					, getTimeLeft(currentAct)));

	}

	@Override
	public void initialWebQuery() {
		super.initialWebQuery();
		if (this.isShareQuery) {
			lastActShareQueryPara = "";

			doShareQuery();
		}
	}

	@Override
	void processTabQuery() {
		super.processTabQuery();

		if (isShareQuery) {

			if (shareTrackData == null)
				doShareQuery();
			else
				showWebTrackListData(shareTrackData);
			if (shareTrackData != null)
				showNoRecText(shareTrackData.size() == 0);
			// }
		} else if (isLiveQuery) {
			// ((LinearLayout)vContainer.findViewById(R.id.tab_map)).setVisibility(
			// View.VISIBLE );

			liveLv.setVisibility(View.VISIBLE);
			showLive();

		}

	}

	@Override
	void switchTabOptions(int queryType) {
		getQueryType(queryType);
		lvWeb.setVisibility(View.GONE);
		bbsbar.setVisibility(isBBSQuery ? View.VISIBLE : View.GONE);
//		imgWebPlus.setVisibility(isBBSQuery ? View.VISIBLE : View.GONE);
		liveMap.setVisibility(isLiveQuery ? View.VISIBLE : View.GONE);
        setNote();
	}

	void getQueryType(int queryType) {
		isBBSQuery = queryType == 0;
		isWebTrackQuery = queryType == 1;
		isMemberQuery = queryType == 2;
		isShareQuery = queryType == 3;
		isLiveQuery = queryType == 4;
//		currentActTab = currentTab;
		roadBookbar.setVisibility(isWebTrackQuery ? View.VISIBLE : View.GONE);		 
	}

	void doWebQuery() { // do roadbook query
	// initialWebListView(R.id.tr_listWeb);

		if (currentAct != null && currentAct.getRoadbooks().size() > 0
				&& trackData == null)

			doWebTrackQuery();
		else if (trackData == null) {
			trackData = new ArrayList<Map<String, String>>();
			showWebTrackListData(trackData);
		}

		/*
		 * if(trackData!=null) showNoRecText(trackData.size()==0);
		 */

	}

	// draw the roadbook
	@Override
	void showWebTrack(Track track) {
		if (isWebTrackQuery) { // show roadbook detail
			super.showWebTrack(track);
			return;
		} else if (isLiveQuery) { // draw gpx on map
			drawActNaviRoadbook(track);
			return;
		} else if (isShareQuery) { // draw gpx on map
			super.showWebTrack(track);
			return;
		}
	}

	@Override
	void showLive() {
		doLiveQuery();

		// show gpx track
		if (currentAct != null && currentAct.getRoadbooks().size() > 0) {
			Track tr = null;
			try {
				tr = activity.app.getTrackCache().get(
						Integer.valueOf(currentAct.getRoadbooks().get(0)));
			} catch (Exception e) {
				Utils.logStackTrace(e, dTAG);
			}
			if (tr == null) {

				if (trackData == null) {
					doWebQuery();
				} else {

					tr = getWebTrackDetail(0);
				}
			}
			drawActNaviRoadbook(tr);

		}

	}

	void drawActNaviRoadbook(Track gpxTrack) {
		if (gpxTrack != null) {
			activity.app.getTrackCache().put(
					gpxTrack.getTrackBean().getSvrNumber(), gpxTrack);
			if (gpxDrawd == null) {
				gpxDrawd = new ArrayList<Integer>();
			}
			drawGpx();
		}
	}

	void showTabButtons(int tabIndex) {

		/*
		 * btn_saveAct.setVisibility(View.GONE);
		 * btn_submitAct.setVisibility(View.GONE);
		 * 
		 * btn_actJoin.setVisibility(View.GONE);
		 * 
		 * 
		 * switch (tabIndex){ case 0: {
		 * btn_saveAct.setVisibility(btn_saveAct.isEnabled
		 * ()?View.VISIBLE:View.GONE);
		 * btn_submitAct.setVisibility(btn_submitAct.
		 * isEnabled()?View.VISIBLE:View.GONE );
		 * btn_actJoin.setVisibility(btn_actJoin
		 * .isEnabled()?View.VISIBLE:View.GONE ); break; } case 1:{ //
		 * btn_saveAct.setVisibility(View.VISIBLE); //
		 * btn_submitAct.setVisibility(View.VISIBLE); //
		 * btn_actJoin.setVisibility(View.VISIBLE); break; } case 2:{
		 * btn_actJoin
		 * .setVisibility(btn_actJoin.isEnabled()?View.VISIBLE:View.GONE);
		 * break; } case 3:{ break; } case 4: { break; } }
		 */
	}

	@Override
	public void setFindResult() {

	}

	@Override
	public void validInputs() {

	}

	@Override
	void processTrackJsonArray(JSONArray jsonArrary) {
		if (isShareQuery) {
			// shareTrackData = getWebTrackList( jsonArrary);
			shareTrackData = getListData(shareTrackData,
					getWebTrackList(jsonArrary));
			showNoRecText(shareTrackData.size() == 0);
			showWebTrackListData(shareTrackData);
		} else/* if(isWebTrackQuery) */{
			// trackData = getWebTrackList( jsonArrary);
			trackData = getListData(trackData, getWebTrackList(jsonArrary));
			showNoRecText(trackData.size() == 0);
			if (!isLiveQuery) { 
				showWebTrackListData(trackData);
				
			}else{
				showLive();
			}
			
		}

	}

	void doShareQuery() {
		Utils.hideSoftKeyboard(activity);
		// noRec.setVisibility(View.GONE);
		this.isShareQuery = true;
		// lvWeb.setVisibility(View.VISIBLE);
		// lv.setVisibility(View.GONE);
		// QLog.getLogger().d(dTAG, TAG+"------begin share query--------- ");

		// getJsonWs(buildQueryParames(),"mb/track/list/"+pageNo);
		// lastWebQueryPara
		// QLog.getLogger().d(dTAG,
		// String.format("firstLoad ？%s,lastActShareQueryPara :%s",firstLoad,
		// lastActShareQueryPara));
		if (this.firstLoad && !TextUtils.isEmpty(lastActShareQueryPara)) {
			return;
		}
		RequestParams param = buildShareQueryParames();
		if (param != null
				&& !lastActShareQueryPara.equalsIgnoreCase(param.toString())) {

			// QLog.getLogger().d(dTAG, lastActShareQueryPara);
			// QLog.getLogger().d(dTAG, param.toString());

			getJsonWs(param, RestMethods.TRACK_G_LIST/*
													 * RestMethods.
													 * TRACK_G_FIND_BY_ACT_GRP
													 *//* "mb/track/list" */);
			lastActShareQueryPara = param.toString();
			selectActShareItem = -1;

		}

	}

	RequestParams buildShareQueryParames() {
		RequestParams params = super.buildTrackQueryParames();
		isShowPic = true;

		if (currentAct != null && currentAct.getSvrNumber() > 0) {
			// QLog.getLogger().d(dTAG, TAG+" act id is : "+
			// currentAct.getSvrNumber());
			params.add("actId", String.valueOf(currentAct.getSvrNumber()));
		}
		// QLog.getLogger().d(dTAG, TAG+" web query params: "+params);

		return params;
	}

	@Override
	RequestParams buildMemberQueryParames() {

		int actId = currentAct == null ? -1 : currentAct.getSvrNumber();

		if (actId <= 0) {
			return null;
		}

		RequestParams params = new RequestParams();// super.buildMemberQueryParames();
		params.add("actId", String.valueOf(actId));
		/*
		 * // String svrNo= edSvrNo.getText().toString();
		 * 
		 * params.add("page", String.valueOf(memberPageNo));
		 * params.add("pagesize", String.valueOf(pageSize));
		 * //QiYouConstant.PV_LAST_LAT,QiYouConstant.PV_LAST_LON
		 * 
		 * // params.add("actid",String.valueOf(actId ));
		 */
		// QLog.getLogger().d(dTAG, TAG+" web query params: "+params);

		return params;
	}

	@Override
	RequestParams buildLiveQueryParames() {
		RequestParams params = new RequestParams();
		// final int GEO_CITY_TYPE=2;

		// if(currentAct==null) return null;
		params.add("actId", String.valueOf(currentAct.getSvrNumber()));
		params.add("from", String.valueOf(lastMaxLiveTime));

		// QLog.getLogger().d(dTAG, TAG+" web query params: "+params);

		return params;
	}

	@Override
	RequestParams buildTrackQueryParames() {

		/*
		 * RequestParams params = new RequestParams(); // final int
		 * GEO_CITY_TYPE=2; isShowPic =true; if(currentAct==null
		 * ||currentAct.getRoadbooks().size()==0 )return null;
		 * params.add("svrNos",
		 * currentAct.getRoadbooks().toString().replace("[", "").replace("]",
		 * "")); params.add("page", String.valueOf(pageNo));
		 * params.add("pagesize", String.valueOf(pageSize)); //
		 * params.add("type", String.valueOf(webTrackType));
		 * params.add("showpic", String.valueOf(isShowPic));
		 * params.add("swidth",
		 * String.valueOf(QiYouConstant.PV_INT_SCREEN_WIDTH));
		 * params.add("sheight",
		 * String.valueOf(QiYouConstant.PV_INT_SCREEN_HEIGHT));
		 * params.add("mytrack", String.valueOf(false));
		 */

		RequestParams params = null;
		if (currentAct != null && currentAct.getRoadbooks().size() > 0) {

			params = super.buildTrackQueryParames();
			params.add("svrNos",
					currentAct.getRoadbooks().toString().replace("[", "")
							.replace("]", ""));
		}else{
			super.showWebTrackListData(new ArrayList<Map<String, String>>() );
//			lvWeb.setVisibility(View.VISIBLE);
		}

		// QLog.getLogger().d(dTAG, TAG+" web query params: "+params);
		return params;
	}

	@Override
	void loadingMore() {
		super.loadingMore();

		/*
		 * if(isLastPage){ return; }
		 */
		if (isShareQuery) {
			lastActShareQueryPara = "";
			pageNo++;
			doShareQuery();
		}

	}
	@Override
	void setNote(){
		 txtNote.setVisibility(View.VISIBLE);
		 String noteTxt =""; 
		
		 if (isBBSQuery){
			 noteTxt = "欢迎来到" + super.BBSsubCateName + "的说说发表高见！";
		 }else if(isWebTrackQuery){
			 noteTxt =     super.BBSsubCateName   + " 相关路书";
		 }else if(isMemberQuery){
			 noteTxt =   super.BBSsubCateName  + "成员";
		 }else if(isShareQuery){
			 noteTxt =  super.BBSsubCateName  + "的运动分享";
		 }else if(isLiveQuery){
			 noteTxt =   super.BBSsubCateName  + "位置直播";
		 }else if(isActivityQuery){
			 noteTxt =   super.BBSsubCateName  + "的相关活动";
		 }else if(super.isGroupQuery){
			 noteTxt =   super.BBSsubCateName  + "的相关队伍";
		 } 
		   
		 if(!TextUtils.isEmpty(noteTxt)){
			 txtNote.setText(noteTxt);
		 }else{
			 txtNote.setVisibility(View.GONE);
		 }
		
	}

//	protected int currentActTab;

	// not to remember last selected tab.
/*	@Override
	protected void setSelectedTab() {
		if (tabhost != null && tabhost.getCurrentTab() != currentTab) {
			tabhost.setCurrentTab(currentTab);
		}
	}
*/
 

	@Override
	public void setTabOnFiling() {
		// TODO Auto-generated method stub
		// int size = currentAct!=null && currentAct.getSvrNumber()>0?4:2;
		maxTabIndex = 5;
		MAPVIEW_INDEX = 5;// currentAct!=null &&
							// currentAct.getSvrNumber()>0?4:-1;
	}

}
