package com.backfire.popupwindow;

import java.util.TreeMap;

import net.yeeyo.doudizhu.feiyu.R;

import org.json.JSONObject;

import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.backfire.doudizhu.ActivityBase;
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.lobby.LobbyActivity;
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 ModifyUserInfoPop extends BasePopupWindow{
	private View view;
	private int width;
	private int height;
	private String icon;
	
	private EditText user_nick;
//	private TextView user_sex;
//	private TextView user_money;
//	private TextView user_gold;
//	private TextView user_email;
//	private TextView user_uid;
//	private TextView user_win_count;
	private EditText user_sign;

	private ImageView info_icon;
	private ImageView info_close;
	
	private EditText bound_email;
	private Button select_submit;
	
	private RadioButton radiomale;
	private RadioButton radiofemale;
	/**
	 * @param activity
	 */
	public ModifyUserInfoPop(ActivityBase activity,String icon) {
		super(activity);
		this.initSetting(icon);
	}
	private void initSetting(String icon){
		LayoutInflater mLayoutInflater = (LayoutInflater) mActivity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		int layoutRourse = R.layout.modify_user_info_pop;
		view = mLayoutInflater.inflate(layoutRourse, null);
		
		view.setFocusableInTouchMode(true);
		 
		user_nick = (EditText) view.findViewById(R.id.user_nick);
		user_sign = (EditText) view.findViewById(R.id.user_sign);

		info_icon = (ImageView) view.findViewById(R.id.info_icon);
		info_close= (ImageView) view.findViewById(R.id.info_close);
		
		bound_email= (EditText) view.findViewById(R.id.bound_email);
		select_submit= (Button) view.findViewById(R.id.select_submit);
		((Button)view.findViewById(R.id.select_submit)).getPaint().setFakeBoldText(true);
		
		radiomale = (RadioButton) view.findViewById(R.id.radiomale);
		radiofemale = (RadioButton) view.findViewById(R.id.radiofemale);
//		
		UserInfo myself = UserMessageCenter.getInstance().getUserInfo();

		if(icon!=null)this.icon = icon;
		else icon = myself.getIcon();
				
		if(myself.getNick()!=null && myself.getNick().trim().length()>0){
			user_nick.setText(myself.getNick());
		}
		if(myself.getEmail()!=null && myself.getEmail().trim().length()>0){
			bound_email.setText(myself.getEmail());
		}

		info_icon.setImageResource(UserMessageCenter.getUserIcon(this.icon));
//		
		if(myself.getSex()==2){
			radiofemale.setChecked(true);
		}else{
			radiomale.setChecked(true);
		}
		if(myself.getSignature()!=null && myself.getSignature().trim().length()>0){
			user_sign.setText(myself.getSignature());
		}
		
		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);
	}
	
	/**
	 * 为各组件设置监听器
	 */
	public void setListens(final LobbyActivity context) {
		select_submit.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				String nick = user_nick.getText().toString();
				if(nick!=null && nick.trim().length()>0){
					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("nick",substring(nick.trim(),10));
					String email = bound_email.getText().toString();
					if(email!=null && email.trim().length()>0){
						email = email.trim();
						String regex="[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9]+(\\.(com|cn|org|edu|hk))";
						if(email.matches(regex)){
							param.put("email",email);
						}else{
							showMessage("您输入的邮箱格式不正确");
							mActivity.playBtnPressMusic();
							return;
						}
					}
					if(radiomale.isChecked()){
						param.put("sex",1);
					}else{
						param.put("sex",2);
					}
					String sign = user_sign.getText().toString();
					if(sign!=null && sign.trim().length()>0){
						param.put("signature",substring(sign.trim(),30));
					}
					param.put("icon",icon);
					String json = new MyJson(param).toString();
					PHPRequestPool.getInstance().AddRequest(new ModifyNickCallback(context),
							PHPMethodName.CLI_MODIFYUSER_REQ, json);
					LoadingProgressDialog.show(mActivity,"修改信息中，请稍等...");
				}else{
					showMessage("昵称不能为空！");
				}
				
				mActivity.playBtnPressMusic();
			}
			
		});
		info_icon.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				CloseWindow();
				IconSelectPopupWindow iconselect = new IconSelectPopupWindow(context);
				iconselect.setListens(context);
				iconselect.ShowWindowInCenter();
				
				mActivity.playBtnPressMusic();
			}
			
		});
		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				CloseWindow();
				return false;
			}
		});
		info_close.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				CloseWindow();
				
				mActivity.playBtnPressMusic();
			}
			
		});
	}
	
	@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
		
	}
	
	private class ModifyNickCallback implements PHPCallbackInterface {
		LobbyActivity mContext;
		public ModifyNickCallback(LobbyActivity context){
			mContext = context;
		}
		public void onFinish(PHPResult result) {
			LoadingProgressDialog.dissmissDlg();
			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){
						UserInfo info = UserMessageCenter.getInstance().getUserInfo();
						info.setNick(substring(user_nick.getText().toString().trim(),10));
						info.setSignature(substring(user_sign.getText().toString().trim(),30));
						info.setIcon(icon);
						info.setEmail(bound_email.getText().toString().trim());
						if(radiomale.isChecked()){
							UserMessageCenter.getInstance().getUserInfo().setSex(1);
						}else{
							UserMessageCenter.getInstance().getUserInfo().setSex(2);
						}
						mContext.notifyModifyMoney();
						CloseWindow();
						showMessage("修改成功");
					}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);
			}
		}
	}
	private void showMessage(String msg){
		//CloseWindow();
		DdzApplication.getApplication().showToast(msg);
	}
	/**
     * 判断一个字符是Ascill字符还是其它字符（如汉，日，韩文字符）
     * 
     * @param char
     *            c, 需要判断的字符
     * @return boolean, 返回true,Ascill字符
     */
    public boolean isLetter(char c) {
        int k = 0x80;
        return c / k == 0 ? true : false;
    }

    /**
     * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
     * 
     * @param String
     *            s ,需要得到长度的字符串
     * @return int, 得到的字符串长度
     */
    public int length(String s) {
        if (s == null)
            return 0;
        char[] c = s.toCharArray();
        int len = 0;
        for (int i = 0; i < c.length; i++) {
            len++;
            if (!isLetter(c[i])) {
                len++;
            }
        }
        return len;
    }

    /**
     * 截取一段字符的长度,不区分中英文,如果数字不正好，则少取一个字符位
     * 
     * @author patriotlml
     * @param String
     *            origin, 原始字符串
     * @param int
     *            len, 截取长度(一个汉字长度按2算的)
     * @return String, 返回的字符串
     */
    public String substring(String origin, int len) {
        if (origin == null || origin.equals("")||len<1)
            return "";
        byte[] strByte = new byte[len];
        if (len > length(origin)){
            return origin;
        }
        System.arraycopy(origin.getBytes(), 0, strByte, 0, len);
        int count = 0;
        for (int i = 0; i < len; i++) {
            int value = (int) strByte[i];
            if (value < 0) {
                count++;
            }
        }
        if (count % 2 != 0) {
            len = (len == 1) ? ++len : --len;
        }
        return new String(strByte, 0, len);
    }
}
