package com.backfire.popupwindow;

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.os.Handler;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.backfire.doudizhu.ActivityBase;
import com.backfire.doudizhu.ActivityThirdPlatform;
import com.backfire.doudizhu.common.DdzApplication;
import com.backfire.doudizhu.common.JSONUtil;
import com.backfire.doudizhu.common.LoadingProgressDialog;
import com.backfire.doudizhu.common.MyJson;
import com.backfire.doudizhu.task.Gift;
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 GiftPopupWindow extends BasePopupWindow {
	private View view;
	private int width;
	private int height;

	private ImageView setting_close;

	private List<Gift> myGifts = null;
	private ListView gift_list;
	private TextView gift_text;
	private MyGiftViewAdapter giftListAdapter = null;

	/**
	 * @param activity
	 */
	public GiftPopupWindow(ActivityBase activity) {
		super(activity);
		this.initSetting();
	}

	private void initSetting() {
		try {
			LayoutInflater mLayoutInflater = (LayoutInflater) mActivity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			int layoutRourse = R.layout.gift_pop;

			view = mLayoutInflater.inflate(layoutRourse, null);

			view.setFocusableInTouchMode(true);

			setting_close = (ImageView) view.findViewById(R.id.info_close);
			gift_text = (TextView) view.findViewById(R.id.gift_text);
			myGifts = new ArrayList<Gift>();
			// init();

			(new Handler()).postDelayed(new Runnable() {

				@Override
				public void run() {
					requestGiftsList();
				}

			}, 100);

			this.setFocusable(true);
			this.setConsumeKeyEvent(true);
			ImageView popupview = (ImageView) view.findViewById(R.id.info_bg);
			width = popupview.getLayoutParams().width;
			height = popupview.getLayoutParams().height;
			this.createPopupWindow(view, width, height);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void requestGiftsList() {
		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 GiftListRequestCallback(),
				PHPMethodName.CLI_GIFT_LIST_REQ, json);
		LoadingProgressDialog.show(mActivity, "正在加载数据中...");
	}

	private void alipayGiftsRequest(int giftID) {
		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("giftID", giftID);

		String json = new MyJson(param).toString();
		PHPRequestPool.getInstance().AddRequest(
				new GiftAlipayRequestCallback(),
				PHPMethodName.CLI_ALIPAY_GIFT_REQ, json);
		LoadingProgressDialog.show(mActivity, "正在加载数据中...");
	}

	private class MyGiftViewAdapter extends BaseAdapter {

		private LayoutInflater mLayoutInflater;

		public MyGiftViewAdapter(Context context) {
			this.mLayoutInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			int count = 0;
			if (myGifts != null) {
				count = myGifts.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) {
			TaskViewHolder holder = null;
			if (convertView == null) {
				holder = new TaskViewHolder();
				convertView = this.mLayoutInflater.inflate(
						R.layout.gift_pop_item, null);

				holder.gift_name = (TextView) convertView
						.findViewById(R.id.gift_name);
				holder.gift_desc = (TextView) convertView
						.findViewById(R.id.gift_desc);
				holder.gift_alipay = (Button) convertView
						.findViewById(R.id.gift_alipay);
				convertView.setTag(holder);
			} else {
				holder = (TaskViewHolder) convertView.getTag();
			}
			Gift gift = myGifts.get(position);
			if (gift != null) {
				// holder.icon.setImageBitmap();
				holder.gift_name.setText(Html.fromHtml(gift.getGiftName()));
				holder.gift_name.getPaint().setFakeBoldText(true);
				holder.gift_desc.setText(Html.fromHtml(gift.getGiftDesc()));
				if (gift.getCanAliPay() == 1) {
					holder.gift_alipay.setText(mActivity
							.getString(R.string.task_alipaying));
					holder.gift_alipay
							.setBackgroundResource(R.drawable.common_btn);
					holder.gift_alipay.setEnabled(true);
					final int giftID = gift.getGiftID();
					holder.gift_alipay
							.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// 领取任务奖励
									alipayGiftsRequest(giftID);

									mActivity.playBtnPressMusic();
								}
							});
				} else if (gift.getCanAliPay() == 2) {
					holder.gift_alipay.setText(mActivity
							.getString(R.string.task_alipayed));
					holder.gift_alipay
							.setBackgroundResource(R.drawable.common_btn);
					holder.gift_alipay.setEnabled(false);
				}
			}
			return convertView;
		}
	}

	private class GiftListRequestCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		public void onFinish(PHPResult result) {
			LoadingProgressDialog.dissmissDlg();
			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 tasksArray = JSONUtil.getJSONArray(res,
									"giftBean");
							if (tasksArray != null && tasksArray.length() > 0) {
								try {
									myGifts.clear();
									for (int i = 0, n = tasksArray.length(); i < n; i++) {
										JSONObject e = tasksArray
												.getJSONObject(i);
										Gift info = new Gift();
										info.setGiftID(JSONUtil.getInt(e,
												"giftID", 0));
										info.setGiftName(JSONUtil.getString(e,
												"giftName", ""));
										info.setGiftDesc(JSONUtil.getString(e,
												"giftDesc", ""));
										info.setCanAliPay(JSONUtil.getInt(e,
												"canAliPay", 0));
										myGifts.add(info);
									}
								} catch (JSONException e) {
									e.printStackTrace();
									String msg = mActivity
											.getString(R.string.network_error);
									showMessage(msg);
								}
							}

							if (myGifts.size() > 0) {
								((ListView) view.findViewById(R.id.gift_list))
										.setVisibility(View.VISIBLE);
								gift_text.setVisibility(View.GONE);
								if (gift_list == null) {
									giftListAdapter = new MyGiftViewAdapter(
											mActivity);
									gift_list = (ListView) view
											.findViewById(R.id.gift_list);
									gift_list.setVerticalScrollBarEnabled(true);
									gift_list.setAdapter(giftListAdapter);
									gift_list.setSelected(true);
									gift_list.setSelection(0);
								} else {
									giftListAdapter.notifyDataSetChanged();
								}
							} else {
								((ListView) view.findViewById(R.id.gift_list))
										.setVisibility(View.GONE);
								gift_text.setVisibility(View.VISIBLE);
								gift_text.setText("暂无礼包赠送！");
							}

						} else {
							// 登录失败
							int retCode = JSONUtil.getInt(res, "retCode", 2);
							String msg = JSONUtil.getString(res, "retMsg", "");
							showMessage(msg + "(" + retCode + ")");
						}
					} else {
						String msg = mActivity
								.getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = mActivity.getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = mActivity.getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}

	private class GiftAlipayRequestCallback implements PHPCallbackInterface {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.backfire.php.PHPCallbackInterface#onFinish(com.backfire.php.PHPResult
		 * )
		 */
		public void onFinish(PHPResult result) {
			LoadingProgressDialog.dissmissDlg();
			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) {
							JSONObject total = JSONUtil.getJSONObject(res,
									"totalmoney");
							if (total != null) {
								UserInfo self = UserMessageCenter.getInstance()
										.getUserInfo();
								self.setMoney(JSONUtil.getLong(total, "money",
										0));
								self.setVip(JSONUtil.getInt(total, "vip", 0));
								self.setVipTime(JSONUtil.getInt(total,
										"vipTime", 0));
								self.setExchangeCard(JSONUtil.getLong(total,
										"exchange", 0));
								self.setLottery(JSONUtil.getLong(total,
										"lottery", 0));
								self.setGiftnumber(self.getGiftnumber() - 1);
							}
							String tipMsg = JSONUtil.getString(res, "tipMsg",
									"");
							try {
								((ActivityThirdPlatform) mActivity)
										.rechargeSuccess(tipMsg);
							} catch (Exception e) {
								Log.i(this, e);
								e.printStackTrace();
							}
							requestGiftsList();
						}
					} else {
						String msg = mActivity
								.getString(R.string.network_error);
						showMessage(msg);
					}
				} else {
					String msg = mActivity.getString(R.string.network_error);
					showMessage(msg);
				}
			} else {
				String msg = mActivity.getString(R.string.network_error);
				showMessage(msg);
			}
		}
	}

	private void showMessage(String msg) {
		DdzApplication.getApplication().showToast(msg);
	}

	/**
	 * 为各组件设置监听器
	 */
	public void setListens() {
		setting_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CloseWindow();

				mActivity.playBtnPressMusic();
			}

		});
		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				CloseWindow();
				return false;
			}
		});
		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float x = event.getX();
				float y = event.getY();

				if (x < 0 || x > width || y < 0 || y > height) {
					CloseWindow();
				}
				return true;
			}
		});
	}

	@Override
	protected boolean popupWindowWillShow() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected void popupWindowDidShow() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void popupWindowWillDissmiss() {
		// TODO Auto-generated method stub

	}

	public final class TaskViewHolder {
		public TextView gift_name; // 任务名称
		public TextView gift_desc; // 任务名称
		public Button gift_alipay; // 领取按钮
	}
}
