package com.backfire.doudizhu.help;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.backfire.doudizhu.ActivityBase;
import com.backfire.doudizhu.ActivityContainer;
import com.backfire.doudizhu.ActivityContainer.ActivityType;
import com.backfire.doudizhu.common.ClickFilter;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.exercise.ExerciseInFo;
import com.backfire.doudizhu.userinfo.UserInfo;
import com.backfire.doudizhu.userinfo.UserMessageCenter;
import com.backfire.php.PHPCallbackInterface;
import com.backfire.php.PHPMethodName;
import com.backfire.php.PHPRequestPool;
import com.backfire.php.PHPResult;
import com.backfire.php.PHPResult.ErrorCode;
import com.backfire.utils.Log;

public class HelpActivity extends ActivityBase{
	
	private RelativeLayout game_rule;
	private RelativeLayout common_request;
	private RelativeLayout connect_us;
	
	private EditText connect_us_text;
	private TextView common_request_no;
	private TextView game_rule_no;
	Drawable bg;
	
	private List<ExerciseInFo> myRules = null;
	private ListView rule_list;
	private RuleListAdapter ruleListAdapter = null;
	
	private List<ExerciseInFo> myQuestions = null;
	private ListView question_list;
	private QuestionListAdapter questionListAdapter = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.help_activity);
		
		bg = new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(
				R.drawable.shop_bg, 
				DdzApplication.getApplication().screenWidth, 
				DdzApplication.getApplication().screenHeight));
		((ImageView) this.findViewById(R.id.activity_bg)).setBackgroundDrawable(bg);
		
		((Button)findViewById(R.id.onClick_game_rule)).getPaint().setFakeBoldText(true);
		((Button)findViewById(R.id.onClick_common_request)).getPaint().setFakeBoldText(true);
		((Button)findViewById(R.id.onClick_connect_us)).getPaint().setFakeBoldText(true);
		((Button)findViewById(R.id.onClick_submit)).getPaint().setFakeBoldText(true);
		game_rule = (RelativeLayout)findViewById(R.id.game_rule);
		common_request = (RelativeLayout)findViewById(R.id.common_request);
		connect_us = (RelativeLayout)findViewById(R.id.connect_us);
		
		connect_us_text = (EditText)findViewById(R.id.connect_us_text);
		
		common_request_no = (TextView)findViewById(R.id.common_request_no);
		game_rule_no = (TextView)findViewById(R.id.game_rule_no);
		
		((ImageView)findViewById(R.id.activity_title_bg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.title_bg, 0, 0)));
		game_rule.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		common_request.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_middle, 0, 0)));
		connect_us.setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_right, 0, 0)));
		
		myRules = new ArrayList<ExerciseInFo>();
		myQuestions = new ArrayList<ExerciseInFo>();
		
		(new Handler()).postDelayed(new Runnable(){

			@Override
			public void run() {
				requestGameRule();
			}
			
		}, 100);
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(){
		ActivityContainer.getInstance().switchTo(this, ActivityType.LOBBY_ACTIVITY);
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(ClickFilter.TestMultiClick())return false;
		if (!this.isFinishing() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			onClick_back();
			return true;
		}
		return super.dispatchKeyEvent(event);
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(View view){
		onClick_back();
	}
	public void onClick_game_rule(View view){
		initView();
		game_rule.setVisibility(View.VISIBLE);
		if(myRules==null || myRules.size()==0){
			game_rule_no.setVisibility(View.GONE);
			requestGameRule();
		}else{
			((ListView)findViewById(R.id.rule_list)).setVisibility(View.VISIBLE);
			game_rule_no.setVisibility(View.GONE);
			if (rule_list == null) {
				ruleListAdapter = new RuleListAdapter(HelpActivity.this);
				rule_list = (ListView)view.findViewById(R.id.rule_list);
				rule_list.setVerticalScrollBarEnabled(true);
				rule_list.setAdapter(ruleListAdapter);
				rule_list.setSelected(true);
				rule_list.setSelection(0);
			}else
			{
				ruleListAdapter.notifyDataSetChanged();
			}
		}
		playBtnPressMusic();
	}
	public void onClick_common_request(View view){
		initView();
		common_request.setVisibility(View.VISIBLE);
		if(myQuestions==null || myQuestions.size()==0){
			common_request_no.setVisibility(View.GONE);
			requestCommon();
		}else{
			((ListView)findViewById(R.id.question_list)).setVisibility(View.VISIBLE);
			common_request_no.setVisibility(View.GONE);
			if (question_list == null) {
				questionListAdapter = new QuestionListAdapter(HelpActivity.this);
				question_list = (ListView)view.findViewById(R.id.question_list);
				question_list.setVerticalScrollBarEnabled(true);
				question_list.setAdapter(questionListAdapter);
				question_list.setSelected(true);
				question_list.setSelection(0);
			}else
			{
				questionListAdapter.notifyDataSetChanged();
			}
		}
		playBtnPressMusic();
	}
	public void onClick_connect_us(View view){
		initView();
		connect_us.setVisibility(View.VISIBLE);
		playBtnPressMusic();
	}
	public void onClick_submit(View view){
		String feedMsg = connect_us_text.getText().toString();
		if(feedMsg==null || feedMsg.trim().length()==0){
			showMessage("请输入反馈信息！");
		}else{
			startLoading("提交反馈信息中...");
			UserInfo self = UserMessageCenter.getInstance().getUserInfo(); 
			TreeMap<String, Object> param = new TreeMap<String, Object>();
			param.put("uid", self.getUid());
			param.put("session",self.getSession());
			param.put("feedBackMsg", feedMsg);
			
			String json = new MyJson(param).toString();
			PHPRequestPool.getInstance().AddRequest(new FeedBackCallback(),
					PHPMethodName.CLI_SUBMIT_FEED_BACK_REQ, json);
		}
	}
	private void requestGameRule(){
		startLoading("加载信息中，请稍等...");
		UserInfo self = UserMessageCenter.getInstance().getUserInfo(); 
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session",self.getSession());
		
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new GameRuleCallback(),
				PHPMethodName.CLI_GAME_RULE_REQ, json);
	}
	private void requestCommon(){
		startLoading("加载信息中，请稍等...");
		UserInfo self = UserMessageCenter.getInstance().getUserInfo(); 
		TreeMap<String, Object> param = new TreeMap<String, Object>();
		param.put("uid", self.getUid());
		param.put("session",self.getSession());
		
		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(new CommonReqCallback(),
				PHPMethodName.CLI_COMMON_REQ, json);
	}
	private void initView(){
		game_rule.setVisibility(View.GONE);
		common_request.setVisibility(View.GONE);
		connect_us.setVisibility(View.GONE);
	}
	public void showMessage(String msg){
		DdzApplication.getApplication().showToast(msg);
	}
	private class FeedBackCallback implements PHPCallbackInterface {

		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
//			if (result != null && result.code == ErrorCode.SUCCESS) {
//				JSONObject res = JSONUtil.parse(result.recvData);
//				if(res!=null){
//					Log.v(this, result.recvData);
//					int ret = JSONUtil.getInt(res, "ret", 2);
//					if(ret==1){
//						showMessage("谢谢您的反馈，我们会尽快处理！");
//					}else{
//						//登陆失败
//						int retCode = JSONUtil.getInt(res, "retCode", 2);
//						String msg =JSONUtil.getString(res, "retMsg", "");
//						showMessage(msg+"("+retCode+")");
//					}
//				}else {
//					String msg = getString(R.string.network_error);
//					showMessage(msg);
//				}
//			} else {
//				String msg = getString(R.string.network_error);
//				showMessage(msg);
//			}
			showMessage("谢谢您的反馈，我们会尽快处理！");
		}
	}
	private class GameRuleCallback implements PHPCallbackInterface {
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if(res!=null){
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if(ret==1){
						JSONArray questionArray = JSONUtil.getJSONArray(res, "gamerule");
						if(questionArray!=null && questionArray.length()>0){
							try {
								myRules.clear();
								for(int i=0,n=questionArray.length();i<n;i++){
									JSONObject e = questionArray.getJSONObject(i);
									ExerciseInFo info = new ExerciseInFo();
									info.setTitle(JSONUtil.getString(e, "title", ""));
									info.setDesc(JSONUtil.getString(e, "desc", ""));
									myRules.add(info);
								}
							} catch (JSONException e) {
								e.printStackTrace();
								String msg = getString(R.string.network_error);
								showMessage(msg);
							}
						}
						
						if(myRules.size()>0){
							((ListView)findViewById(R.id.rule_list)).setVisibility(View.VISIBLE);
							common_request_no.setVisibility(View.GONE);
							if (rule_list == null) {
								ruleListAdapter = new RuleListAdapter(HelpActivity.this);
								rule_list = (ListView)findViewById(R.id.rule_list);
								rule_list.setVerticalScrollBarEnabled(true);
								rule_list.setAdapter(ruleListAdapter);
								rule_list.setSelected(true);
								rule_list.setSelection(0);
							}else
							{
								ruleListAdapter.notifyDataSetChanged();
							}
						}else{
							((ListView)findViewById(R.id.rule_list)).setVisibility(View.GONE);
							game_rule_no.setVisibility(View.VISIBLE);
							game_rule_no.setText("暂无常见问题解说");
						}

					}else{
						//登陆失败
						int retCode = JSONUtil.getInt(res, "retCode", 2);
						String msg =JSONUtil.getString(res, "retMsg", "");
						showMessage(msg+"("+retCode+")");
					}
				}else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}
	private class CommonReqCallback implements PHPCallbackInterface {
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if (result != null && result.code == ErrorCode.SUCCESS) {
				JSONObject res = JSONUtil.parse(result.recvData);
				if(res!=null){
					Log.v(this, result.recvData);
					int ret = JSONUtil.getInt(res, "ret", 2);
					if(ret==1){
						
						JSONArray questionArray = JSONUtil.getJSONArray(res, "commonedesc");
						if(questionArray!=null && questionArray.length()>0){
							try {
								myQuestions.clear();
								for(int i=0,n=questionArray.length();i<n;i++){
									JSONObject e = questionArray.getJSONObject(i);
									ExerciseInFo info = new ExerciseInFo();
									info.setTitle(JSONUtil.getString(e, "title", ""));
									info.setDesc(JSONUtil.getString(e, "desc", ""));
									myQuestions.add(info);
								}
							} catch (JSONException e) {
								e.printStackTrace();
								String msg = getString(R.string.network_error);
								showMessage(msg);
							}
						}
						
						if(myQuestions.size()>0){
							((ListView)findViewById(R.id.question_list)).setVisibility(View.VISIBLE);
							common_request_no.setVisibility(View.GONE);
							if (question_list == null) {
								questionListAdapter = new QuestionListAdapter(HelpActivity.this);
								question_list = (ListView)findViewById(R.id.question_list);
								question_list.setVerticalScrollBarEnabled(true);
								question_list.setAdapter(questionListAdapter);
								question_list.setSelected(true);
								question_list.setSelection(0);
							}else
							{
								questionListAdapter.notifyDataSetChanged();
							}
						}else{
							((ListView)findViewById(R.id.question_list)).setVisibility(View.GONE);
							common_request_no.setVisibility(View.VISIBLE);
							common_request_no.setText("暂无常见问题解说");
						}
						
					}else{
						//登陆失败
						int retCode = JSONUtil.getInt(res, "retCode", 2);
						String msg =JSONUtil.getString(res, "retMsg", "");
						showMessage(msg+"("+retCode+")");
					}
				}else {
					String msg = getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}

	private class QuestionListAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public QuestionListAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		public int getCount() {
			int count = 0;
			if (myQuestions != null) {
				count =  myQuestions.size();
			}
			return count;
		}
		public Object getItem(int position) {
			return null;
		}
		public long getItemId(int position) {
			return 0;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			QuestionViewHolder holder = null;
			if( convertView == null)
			{
				holder = new QuestionViewHolder();
				convertView = this.mLayoutInflater.inflate(R.layout.exer_list_item, null);
				
				holder.title = (TextView)convertView.findViewById(R.id.title);
				holder.desc = (TextView)convertView.findViewById(R.id.desc);
				convertView.setTag(holder);
			}
			else
			{
				holder = (QuestionViewHolder)convertView.getTag();
			}
			ExerciseInFo question = myQuestions.get(position);
			if (question != null) {
				//holder.icon.setImageBitmap();
				holder.title.setText(Html.fromHtml(question.getTitle()));
				holder.desc.setText(Html.fromHtml(question.getDesc()));
			}
			return convertView;
		}
	}
	public final class QuestionViewHolder {
		public TextView title; 		// 标题
		public TextView desc; 			//描述
	}
	private class RuleListAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public RuleListAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		public int getCount() {
			int count = 0;
			if (myRules != null) {
				count =  myRules.size();
			}
			return count;
		}
		public Object getItem(int position) {
			return null;
		}
		public long getItemId(int position) {
			return 0;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			QuestionViewHolder holder = null;
			if( convertView == null)
			{
				holder = new QuestionViewHolder();
				convertView = this.mLayoutInflater.inflate(R.layout.exer_list_item, null);
				
				holder.title = (TextView)convertView.findViewById(R.id.title);
				holder.desc = (TextView)convertView.findViewById(R.id.desc);
				convertView.setTag(holder);
			}
			else
			{
				holder = (QuestionViewHolder)convertView.getTag();
			}
			ExerciseInFo question = myRules.get(position);
			if (question != null) {
				//holder.icon.setImageBitmap();
				holder.title.setText(Html.fromHtml(question.getTitle()));
				holder.desc.setText(Html.fromHtml(question.getDesc()));
			}
			return convertView;
		}
	}

}

