package com.gh.gamecenter;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.common.constant.Config;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.PackageUtils;

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

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fang
 * @from SettingActivity
 * @function 填写反馈页面
 * 
 * */
public class SuggestionActivity extends BaseActivity implements OnClickListener {

	public static final String TAG = SuggestionActivity.class.getSimpleName();

	private TextView tv_suggest_connectway;
	private EditText et_suggest_content, et_suggest_connectway;
	private CardView btn_suggest_post;

	private boolean isShowing = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		View contentView = View.inflate(this, R.layout.activity_suggest, null);

		init(contentView, "意见反馈");

		btn_suggest_post.setOnClickListener(this);
		btn_suggest_post.setClickable(false);

		et_suggest_content.requestFocus();

		tv_suggest_connectway.setText("邮箱");

		et_suggest_content.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s.length() > 0) {
					btn_suggest_post.setClickable(true);
				} else {
					btn_suggest_post.setClickable(false);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.actionbar_rl_back:
			finish();
			break;
		case R.id.btn_suggest_post:
			String email = et_suggest_connectway.getText().toString().trim();
			if (TextUtils.isEmpty(email)) {
				showConfirmDialog(email);
			} else if (isEmailAddress(email)) {
				isShowing = true;
				Dialog dialog = new Dialog(this);
				View view = View.inflate(this, R.layout.set_wait_dialog, null);
				TextView message = (TextView) view
						.findViewById(R.id.set_wait_message);
				message.setText("正在反馈...");
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(view);
				dialog.setCanceledOnTouchOutside(false);
				dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						if (isShowing) {
							AppController.canclePendingRequests(TAG);
							toast("取消发送");
						}
					}
				});
				dialog.show();
				sendSuggestion(dialog, email);
			} else {
				toast("邮箱错误");
			}
			break;
		default:
			break;
		}
	}

	// 弹出确认对话框
	private void showConfirmDialog(final String email) {
		DialogUtils.showWarningDialog(this, "温馨提示", "填写联系方式有助于我们更好地一对一解决您的问题，确定不填写吗？",
				"直接提交", "我要填写",
				new DialogUtils.ConfiremListener() {
					@Override
					public void onConfirem() {
						et_suggest_connectway.requestFocus();
						new Thread() {
							public void run() {
								try {
									sleep(300);
								} catch (InterruptedException e) {

									e.printStackTrace();
								}
								InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
								imm.showSoftInput(et_suggest_connectway, 0);
							}
						}.start();
					}
				},
				new DialogUtils.CancelListener() {
					@Override
					public void onCancel() {
						isShowing = true;
						Dialog dialog = new Dialog(SuggestionActivity.this);
						View view = View.inflate(SuggestionActivity.this,
								R.layout.set_wait_dialog, null);
						TextView message = (TextView) view
								.findViewById(R.id.set_wait_message);
						message.setText("正在反馈...");
						dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						dialog.setContentView(view);
						dialog.setCanceledOnTouchOutside(false);
						dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
							@Override
							public void onDismiss(DialogInterface dialog) {
								if (isShowing) {
									AppController.canclePendingRequests(TAG);
									toast("取消发送");
								}
							}
						});
						dialog.show();
						sendSuggestion(dialog, email);
					}
				});
	}

	private void sendSuggestion(final Dialog dialog, String email) {
		Map<String, String> map = new HashMap<>();
		map.put("message", et_suggest_content.getText().toString().trim());
		map.put("from", email);
		map.put("ghversion", PackageUtils.getVersion(this));
		map.put("channel", (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID"));
		map.put("type", android.os.Build.MODEL);
		map.put("sdk", String.valueOf(android.os.Build.VERSION.SDK_INT));
		map.put("version", android.os.Build.VERSION.RELEASE);
		map.put("imei", ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId());
		JsonObjectRequest request = new JsonObjectRequest(Method.POST,
				Config.HOST + "v1d46/support/suggestion", new JSONObject(map),
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject object) {
						isShowing = false;
						dialog.dismiss();

						try {
							if ("ok".equals(object.getString("status"))) {
								toast("提交成功，感谢您的反馈！");
								finish();
							} else {
								toast("提交失败，请稍后尝试！");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						isShowing = false;
						dialog.dismiss();
						toast("提交失败，请检查网络状态");
					}
				});
		request.setShouldCache(false);
		AppController.addToRequestQueue(request, TAG);
	}

	private boolean isEmailAddress(String email) {
		Pattern p = Pattern
				.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
		Matcher m = p.matcher(email);
		return m.matches();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		tv_suggest_connectway = null;
		et_suggest_content = null;
		et_suggest_connectway = null;
		btn_suggest_post = null;
	}
}
