package com.usai.apex;

import com.usai.util.Network;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class RetrievePasswordActivity extends Activity
{

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask	mAuthTask	= null;

	// Values for email and password at the time of the login attempt.
	private String			m_sEmail;
	private String			m_sUser;

	// UI references.
	private EditText		mEmailView;
	private EditText		m_userView;
	private View			mLoginFormView;
	private View			mLoginStatusView;
	private TextView		mLoginStatusMessageView;

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

		setContentView(R.layout.activity_retrieve_password);

		// Set up the login form.
		m_userView = (EditText) findViewById(R.id.user);
		// m_sEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		// mEmailView.setText(m_sEmail);

		mEmailView
				.setOnEditorActionListener(new TextView.OnEditorActionListener()
				{
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent)
					{
						if (id == R.id.btn_ok
								|| id == EditorInfo.IME_ACTION_DONE)
						{

							InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext()
									.getSystemService(
											Context.INPUT_METHOD_SERVICE);

							// EditText editText =
							// (EditText)findViewById(R.id.xxxx);
							inputMethodManager.hideSoftInputFromWindow(
									mEmailView.getWindowToken(), 0); // ����
							retrivev();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view)
			{
				InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext()
						.getSystemService(Context.INPUT_METHOD_SERVICE);

				// EditText editText =
				// (EditText)findViewById(R.id.xxxx);
				inputMethodManager.hideSoftInputFromWindow(
						mEmailView.getWindowToken(), 0); // ����
				retrivev();
			}
		});
		findViewById(R.id.btn_close).setOnClickListener(
				new View.OnClickListener()
				{
					@Override
					public void onClick(View view)
					{
						finish();
					}
				});
	}

	//
	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// super.onCreateOptionsMenu(menu);
	// getMenuInflater().inflate(R.menu.retrieve_password, menu);
	// return true;
	// }

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void retrivev()
	{
		if (mAuthTask != null)
		{
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		m_userView.setError(null);

		// Store values at the time of the login attempt.
		m_sEmail = mEmailView.getText().toString();
		m_sUser = m_userView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(m_sUser))
		{
			m_userView.setError(getString(R.string.error_field_required));
			focusView = m_userView;
			cancel = true;
		}
		// else if (m_sUser.length() < 4) {
		// m_userView.setError(getString(R.string.error_invalid_password));
		// focusView = m_userView;
		// cancel = true;
		// }

		// Check for a valid email address.
		if (TextUtils.isEmpty(m_sEmail))
		{
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		}
		else if (!m_sEmail.contains("@"))
		{
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel)
		{
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		}
		else
		{
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show)
	{
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
		{
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter()
					{
						@Override
						public void onAnimationEnd(Animator animation)
						{
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter()
					{
						@Override
						public void onAnimationEnd(Animator animation)
						{
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		}
		else
		{
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
	{
		int	errorcode;

		@Override
		protected Boolean doInBackground(Void... params)
		{
			errorcode = Network.retrieve_pass(m_sUser, m_sEmail);
			if (errorcode == Network.RESULT_TRUE)
				return true;
			else
			{
				return false;
			}

		}

		@Override
		protected void onPostExecute(final Boolean success)
		{
			Log.d("onPostExecute", "entry");
			mAuthTask = null;
			showProgress(false);
			// if (netconnect == )
			// {
			//
			// }

			if (success)
			{
				AlertDialog.Builder builder = new Builder(
						RetrievePasswordActivity.this);
				builder.setMessage(getString(R.string.str_email_sent));

				builder.setTitle(getString(R.string.str_retrieve_success));

				builder.setPositiveButton(getString(android.R.string.ok), new OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();

						RetrievePasswordActivity.this.finish();
					}
				});

				// builder.setNegativeButton("取消", new OnClickListener() {
				//
				// @Override
				// public void onClick(DialogInterface dialog, int which) {
				// dialog.dismiss();
				// }
				// });

				builder.create().show();

			}
			else
			{
				switch (errorcode)
				{
					case Network.RESULT_NET_NOTAVAILABLE:
					{
						Toast toast = Toast.makeText(getApplicationContext(),
								getText(R.string.msg_connection_none),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						return;
					}
					case Network.RESULT_NET_ERROR:
					{
						Toast toast = Toast.makeText(getApplicationContext(),
								getText(R.string.msg_net_error),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						return;
					}
					case Network.RESULT_ERROR:
					// case Network.RESULT_RESPONSE_NULL:
					{
						Toast toast = Toast.makeText(getApplicationContext(),
								getText(R.string.msg_net_resulterror),
								Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						return;
					}

					case Network.RESULT_FALSE:
					{
						AlertDialog.Builder builder = new Builder(
								RetrievePasswordActivity.this);
						builder.setMessage(getString(R.string.str_invalid_pore));

						builder.setTitle(getString(R.string.str_retrieve_failed));

						builder.setPositiveButton(getString(android.R.string.ok), new OnClickListener()
						{

							@Override
							public void onClick(DialogInterface dialog,
									int which)
							{
								dialog.dismiss();

								// RetrievePasswordActivity.this.finish();
							}
						});
						builder.create().show();
						return;

					}
					default:
					{
						Toast toast = Toast.makeText(getApplicationContext(),
								getText(R.string.msg_net_resulterror) + ":"
										+ errorcode, Toast.LENGTH_LONG);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
						break;
					}
				}
			}
		}

		@Override
		protected void onCancelled()
		{
			mAuthTask = null;
			showProgress(false);
		}
	}
}
