package jp.agentec.abook.abv.ui.home.activity;

import jp.agentec.abook.abv.bl.common.exception.ABVException;
import jp.agentec.abook.abv.bl.common.exception.ABVExceptionCode;
import jp.agentec.abook.abv.bl.common.exception.NetworkDisconnectedException;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.UserAuthenticateLogic;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVNoAuthenticatedActivity;
import jp.agentec.abook.abv.ui.common.constant.ErrorCode;
import jp.agentec.abook.abv.ui.common.constant.ErrorMessage;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.adf.util.StringUtil;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class LoginPasswordChangeActivity extends ABVNoAuthenticatedActivity {
	private static final String TAG = "LoginPasswordChangeActivity";
	private EditText mEdtLoginId;
	private EditText mEdtPwdNow;
	private EditText mEdtPwdNew;
	private EditText mEdtPwdReNew;
	
	private TextView mTextViewTitle;

	private Button mBtnPasswordChange;
	private Button mBtnCancel;
	
	private String mLoginId;
    private String mPassword;
	private int mType;

	@Override
    public void onCreate(Bundle savedInstanceState) {
		Logger.i(TAG, "onCreate");

		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
        mLoginId = intent.getStringExtra("loginId");
        mPassword = intent.getStringExtra("password");
        mType = intent.getIntExtra("type", -1);
		Logger.d("LoginPasswordChangeActivity.mType="+ mType); // 1, 2:催促　3, 4：強制 TODO later 区別する必要があるか？ Jang

		setContentView(R.layout.ac_login_change_password);
		
		if (mType == 4) {
			mEdtLoginId = (EditText) findViewById(R.id.edt_id);
			mEdtLoginId.setVisibility(View.VISIBLE);
			mEdtLoginId.setText(mLoginId);
		}

		mEdtPwdNow = (EditText) findViewById(R.id.edt_pwd_now);
		mEdtPwdNew = (EditText) findViewById(R.id.edt_pwd_new);
		mEdtPwdReNew = (EditText) findViewById(R.id.edt_pwd_renew);
		
		mTextViewTitle =(TextView)findViewById(R.id.password_change_title);

		mBtnPasswordChange = (Button) findViewById(R.id.btn_password_change);
		mBtnCancel = (Button) findViewById(R.id.btn_cancel);
		
		mBtnPasswordChange.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				passwordChange();
			}
		});

		mBtnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mType == 1 || mType == 2) {
					// 催促
					showMainActivity(mLoginId);
					finish();
				} else {
					finishActivity();
				}
			}
		});

		CheckBox checkBox = (CheckBox) findViewById(R.id.show_password);
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				EditText edtPwdNow = (EditText) findViewById(R.id.edt_pwd_now);
				EditText edtPwdNew = (EditText) findViewById(R.id.edt_pwd_new);
				EditText edtPwdReNew = (EditText) findViewById(R.id.edt_pwd_renew);

				// カーソル位置の保存
				int edtPwdNowSelection = edtPwdNow.getSelectionEnd();
				int edtPwdNewNowSelection = edtPwdNew.getSelectionEnd();
				int edtPwdReNewSelection = edtPwdReNew.getSelectionEnd();

				if (isChecked) {
					Logger.d(TAG, "Password Show ON");
					edtPwdNow.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
					edtPwdNew.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
					edtPwdReNew.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				} else {
					Logger.d(TAG, "Password Show OFF");
					edtPwdNow.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
					edtPwdNew.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
					edtPwdReNew.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				}

				// カーソル位置の復元
				edtPwdNow.setSelection(edtPwdNowSelection);
				edtPwdNew.setSelection(edtPwdNewNowSelection);
				edtPwdReNew.setSelection(edtPwdReNewSelection);
			}
		});
	}
	
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
    		finishActivity();
	    } else  {
			return super.onKeyUp(keyCode, event);
		}
    	return false;
    }
    
    private void finishActivity() {
		Intent intent = new Intent();
		intent.setClassName(getApplicationContext().getPackageName(), LoginActivity.class.getName()).setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		startActivity(intent);
		finish();
    }
    
    private void passwordChange() {

    	String password_now = mEdtPwdNow.getText().toString();
		String password_new = mEdtPwdNew.getText().toString();
		String password_renew = mEdtPwdReNew.getText().toString();
		
		if (StringUtil.isNullOrEmpty(password_now)) {
			ABVToastUtil.showMakeText(LoginPasswordChangeActivity.this, getString(R.string.E101), Toast.LENGTH_LONG);
			mTextViewTitle.setText(R.string.E101);
			return ;
		}
		if (StringUtil.isNullOrEmpty(password_new)) {
			ABVToastUtil.showMakeText(LoginPasswordChangeActivity.this, getString(R.string.E102), Toast.LENGTH_LONG);
			mTextViewTitle.setText(R.string.E102);
			return;
		}
		if (StringUtil.isNullOrEmpty(password_renew)) {
			ABVToastUtil.showMakeText(LoginPasswordChangeActivity.this, getString(R.string.E103), Toast.LENGTH_LONG);
			mTextViewTitle.setText(R.string.E103);
			return;
		}
		if (!password_new.equals(password_renew)) {
			ABVToastUtil.showMakeText(LoginPasswordChangeActivity.this, getString(R.string.E104), Toast.LENGTH_LONG);
			mTextViewTitle.setText(R.string.E104);
			return;
		}
		
		try {
			UserAuthenticateLogic userservice = AbstractLogic.getLogic(UserAuthenticateLogic.class);
			userservice.changePassword(mEdtPwdNow.getText().toString(), mEdtPwdNew.getText().toString(), false);

			ABVToastUtil.showMakeText(LoginPasswordChangeActivity.this, getString(R.string.change_password_ok), Toast.LENGTH_LONG);

			showMainActivity(mLoginId);
			finish();
		} catch (NetworkDisconnectedException e) {
			Logger.e("NetworkDisconnectedException", e);
			handleErrorMessageToast(ErrorCode.NETWORK);
		} catch (ABVException e) {
			Logger.e("ABVException", e.toString());
			if (e.getCode().equals(ABVExceptionCode.C_E_SECURITY_1005)) {
				handleErrorMessageToast(ErrorCode.E111);
				mEdtPwdNow.setText("");
				mEdtPwdNow.requestFocus();
			}
			else if (e.getCode().equals(ABVExceptionCode.S_E_ACMS_0400)) {
				handleErrorMessageToast(e.getMessage());
			} else {
				handleErrorMessageToast(ErrorMessage.getErrorCode(e));
			}
		} catch (IllegalArgumentException e) {
			Logger.e("IllegalArgumentException", e);
			handleErrorMessageToast(ErrorCode.E110);
		} catch (Exception e) {
			Logger.e("Exception ", e);
			handleErrorMessageToast(ErrorCode.E107);

			Intent intent = new Intent();
			String className = LoginActivity.class.getName();
			intent.setClassName(getApplicationContext().getPackageName(), className).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		}

    }
	@Override
	public void onResume() {
		Logger.i(TAG, "onResume");
		super.onResume();
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	}

	@Override
	protected View getContentViewId() {
		return null;
	}

	@Override
	protected void onPasswordChanged() {}

	@Override
	protected void goNext() {}

}
