package com.wasu.cs.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.common.WError;
import com.wasu.cs.widget.ErrorDialog;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;

import basic.update.present.UpdatePresent;
import basic.update.view.AppStartUpdateView;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;
import cn.com.wasu.main.systeminfo.DialogSystemInfo;

/**
 * 注册协议页
 * 
 * @author Administrator
 * 
 */
public class ActivityRegister extends ActivityBase {

	private final static String TAG = "ActivityRegister";
	private Context mContext;
	private long exitTime = 0;
	private AuthListener authListener;

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

		WLog.i(TAG,"onCreate()");

		//check wether need to update
		UpdatePresent.getInstance().checkWhetherNeedUpdate(new AppStartUpdateView());
	}

	// 不需要检测授权
	@Override
	protected int checkAuthState() {
		return AUTH_CHECK_CANCEL;
	}

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		setContentView(R.layout.activity_register);
		mContext = this;
		initView();

	}

	private void initView() {
		TextView mArticleTextView = (TextView) findViewById(R.id.txt_state);

		mArticleTextView.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					v.setScrollbarFadingEnabled(false);
				} else {
					v.setScrollbarFadingEnabled(true);
				}
			}
		});

		mArticleTextView.setMovementMethod(new ScrollingMovementMethod() {

			@Override
			protected boolean up(TextView widget, Spannable buffer) {
				if (super.up(widget, buffer)) {
					WLog.i(TAG, "up()");

					return true;
				} else {
					return false;
				}
			}

			@Override
			protected boolean down(TextView widget, Spannable buffer) {
				if (super.down(widget, buffer)) {
					WLog.i(TAG, "down()");

					return true;
				} else {
					return false;
				}
			}

		});

		final TextView btn_agree = (TextView) findViewById(R.id.btn_agree);

		mArticleTextView.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				switch (keyCode) {
				case KeyEvent.KEYCODE_DPAD_RIGHT:
					btn_agree.requestFocus();
					return true;
				}
				return false;
			}
		});

		btn_agree.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (checkNetConnect()) {
					auth();
				} else {
					showErrorExitDlg(ErrorMap.mapError(mContext, WError.makeError(WError.MODULE_HTTP, WError.ERROR_NET), null));
				}

			}
		});

		mArticleTextView.requestFocus();
	}

	private void auth() {
		showLoading();
		WasuStatistics.getInstance().registBegin();
		authListener= new AuthListener() {//添加引用，解决匿名类导致的内存泄露问题

			@Override
			public void result(int ret, String extra, Object retData) {
				String success = "0";
				if (ret == WError.ERROR_NONE) {
					//deviceRegister success
					WLog.i(TAG,"deviceRegister()  success");

					success = "1";
					WasuStatistics.getInstance().loadBegin();

					//device login
					AuthSDK.getInstance().deviceLogin(new AuthListener() {

						@Override
						public void result(int ret, String extra, Object retData) {

							String success_load = "0";
							if (ret == WError.ERROR_NONE) {
								WLog.i(TAG,"deviceLogin()  success");

								success_load = "1";

								WLog.i(TAG,"jumpto	ActivityGuide");

								jumpToNextAct(ActivityGuide.class);
								hideLoading();
								finish();

							} else {
								WLog.i(TAG,"deviceLogin()  failed");

								success_load = "0";
								hideLoading();
								if (ret == WError.ERROR_UPM_NOT_AUTH) {
									IntentMap.startIntent(ActivityRegister.this, null, null, null, ActivityServiceStop.class);
									finish();
									return;
								} else {
									showAuthError("设备登录失败!如有疑问，请联系客服");
								}
							}
							WasuStatistics.getInstance().loadEnd(success_load);
						}
					});
				} else {
					//deviceRegister failed
					WLog.i(TAG,"deviceRegister()  failed");

					success = "0";

					hideLoading();
					if (ret == WError.ERROR_UPM_NOT_AUTH) {
						//UPM refused to auth. that means this product line is stopped
						IntentMap.startIntent(ActivityRegister.this, null, null, null, ActivityServiceStop.class);
						finish();
					} else {
						showAuthError("设备注册失败!如有疑问，请联系客服");
					}

				}
				WasuStatistics.getInstance().registEnd(success);
			}
		};

		AuthSDK.getInstance().deviceRegister(authListener);
		WLog.i(TAG,"begin to do deviceRegister()");
	}

	/**
	 * 授权出错
	 * 
	 * @param msg
	 */
	private void showAuthError(String msg) {
		hideLoading();
		Dialog dlgAuth = new ErrorDialog.mBuilder(this)

		.setMessage(msg).addBtn1("退出", new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				finish();

			}
		}).addBtn2("重试", new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				auth();

			}
		}).create();

		dlgAuth.setCancelable(false);
		dlgAuth.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (authListener != null) {
			authListener = null;
		}
	}

	/**
	 * 跳转activity
	 */
	private void jumpToNextAct(Class<?> targetClass) {
		Intent i = getIntent();
		if (i == null) {
			i = new Intent();
		}

		String layoutCode = i.getStringExtra(IntentConstant.LAYOUT_CODE.value());
		String jsonUrl = i.getStringExtra(IntentConstant.DATAURI.value());

		IntentMap.startIntent(this, i, layoutCode, jsonUrl, targetClass);
	}

	/**
	 * 退出app
	 */
	public void exitApp() {
		if (exitTime != 0 && System.currentTimeMillis() - exitTime <= Common.EXIT_DURATION) {
			this.finish();
		} else {
			Toast.makeText(mContext, getString(R.string.exit_message), Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case MSG_RESET_MENUKEYCLICKEDCOUNT:
				menuKeyClickedCount = 0;
				break;

			}
		}
	};
	/** 记录menu点击的次数 **/
	private int menuKeyClickedCount = 0;
	/** 延迟半秒发送置空menu点击的次数的msg.what **/
	private static final int MSG_RESET_MENUKEYCLICKEDCOUNT = 0;

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_MENU) {
			/**
			 * 8次点击menu，两次之间的间隔时间只有小于半秒才能累计点击次数，不然会被置0
			 * 间隔小于半秒，就会removeMsg，这样点击次数就不会被置0，
			 * 如果间隔大于半秒，就算removeMsg也没有用，因为点击次数已经置0了
			 **/
			mHandler.removeMessages(MSG_RESET_MENUKEYCLICKEDCOUNT);
			if (++menuKeyClickedCount == 8) {
				Dialog dialogSystemInfo = new DialogSystemInfo(this);
				dialogSystemInfo.show();
				/** menu点击次数置0 **/
				menuKeyClickedCount = 0;
			} else {
				/** 延迟半秒才发生msg **/
				mHandler.sendEmptyMessageDelayed(MSG_RESET_MENUKEYCLICKEDCOUNT, 500);
			}
		}
		return super.dispatchKeyEvent(event);
	}
}
