package com.backfire.doudizhu.exercise;

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.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.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 ExerciseActivity extends ActivityBase{
	private List<ExerciseInFo> myExers = null;
	private ListView exercise_list;
	private TextView exercise_text;
	private MyExerViewAdapter ExerListAdapter = null;
	Drawable bg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exercise_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_exercise)).getPaint().setFakeBoldText(true);
		exercise_text = (TextView)findViewById(R.id.exercise_text);
		myExers = new ArrayList<ExerciseInFo>();
		
		((ImageView)findViewById(R.id.activity_title_bg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.title_bg, 0, 0)));
		
		((RelativeLayout)findViewById(R.id.exercise_msg)).setBackgroundDrawable(
				new BitmapDrawable(DdzApplication.getApplication().getBmpPool().getBitmap(R.drawable.help_list_bg_left, 0, 0)));
		//init();
		(new Handler()).postDelayed(new Runnable(){

			@Override
			public void run() {
		requestExersList();
	}
			
		}, 100);
	}
	private void requestExersList(){
		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 ExerListRequestCallback(), PHPMethodName.CLI_EXER_REQ, json);
		startLoading("正在加载数据中...");
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(){
		ActivityContainer.getInstance().switchTo(this, ActivityType.LOBBY_ACTIVITY);
	}
	/*
	 * 返回按钮对应的处理方法
	 */
	public void onClick_back(View view){
		onClick_back();
	}
	@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);
	}
	
	private class MyExerViewAdapter extends BaseAdapter
	{
		
		private LayoutInflater mLayoutInflater;
		public MyExerViewAdapter(Context context)
		{
			this.mLayoutInflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			int count = 0;
			if (myExers != null) {
				count =  myExers.size();
			}
			return count;
		}
		@Override
		public Object getItem(int position) {
			return null;
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			NoticeViewHolder holder = null;
			if( convertView == null)
			{
				holder = new NoticeViewHolder();
				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 = (NoticeViewHolder)convertView.getTag();
			}
			ExerciseInFo exercise = myExers.get(position);
			if (exercise != null) {
				//holder.icon.setImageBitmap();
				holder.title.setText(Html.fromHtml(exercise.getTitle()));
				holder.desc.setText(Html.fromHtml(exercise.getDesc()));
			}
			return convertView;
		}
	}
	private class ExerListRequestCallback implements PHPCallbackInterface
	{
		/* (non-Javadoc)
		 * @see com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult)
		 */
		@Override
		public void onFinish(PHPResult result) {
			stopLoading();
			if(result != null && result.code == ErrorCode.SUCCESS)
			{
				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 exersArray = JSONUtil.getJSONArray(res, "exercises");
							if(exersArray!=null && exersArray.length()>0){
								try {
									for(int i=0,n=exersArray.length();i<n;i++){
										JSONObject e = exersArray.getJSONObject(i);
										ExerciseInFo info = new ExerciseInFo();
										info.setTitle(JSONUtil.getString(e, "title", ""));
										info.setDesc(JSONUtil.getString(e, "desc", ""));
										myExers.add(info);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = getString(R.string.network_error);
									showMessage(msg);
								}
							}
							if(myExers.size()>0){
								((ListView)findViewById(R.id.exercise_list)).setVisibility(View.VISIBLE);
								exercise_text.setVisibility(View.GONE);
								if (exercise_list == null) {
									ExerListAdapter = new MyExerViewAdapter(ExerciseActivity.this);
									exercise_list = (ListView)findViewById(R.id.exercise_list);
									exercise_list.setVerticalScrollBarEnabled(true);
									exercise_list.setAdapter(ExerListAdapter);
									exercise_list.setSelected(true);
									exercise_list.setSelection(0);
								}else
								{
									ExerListAdapter.notifyDataSetChanged();
								}
							}else{
								((ListView)findViewById(R.id.exercise_list)).setVisibility(View.GONE);
								exercise_text.setVisibility(View.VISIBLE);
								exercise_text.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);
				}
			}else{
				String msg = getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}
	
	public void showMessage(String msg){
		DdzApplication.getApplication().showToast(msg);
	}
	
	public final class NoticeViewHolder {
		public TextView title; 		// 标题
		public TextView desc; 			//描述
	}
	public final class PerInFoViewHolder {
		public TextView desc; 			//描述
		public  Button deliver; 		// 领取按钮
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 if(bg!=null)bg.setCallback(null);
			if(myExers!=null){
				myExers.clear();
				myExers = null;
			}
			exercise_list = null;
			ExerListAdapter = null;
	}
}


