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

import jp.agentec.abook.abv.bl.acms.client.json.CmsUrlJSON;
import jp.agentec.abook.abv.bl.acms.type.DeleteDataType;
import jp.agentec.abook.abv.bl.acms.type.LoginMode;
import jp.agentec.abook.abv.bl.acms.type.LoginStatus;
import jp.agentec.abook.abv.bl.acms.type.RequirePasswordChangeCode;
import jp.agentec.abook.abv.bl.acms.type.RequirePasswordChangeType;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.CommonExecutor;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.bl.common.Constant.DeviceType;
import jp.agentec.abook.abv.bl.common.Constant.ExceptionDetailMessage;
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.AcmsException;
import jp.agentec.abook.abv.bl.common.exception.NetworkDisconnectedException;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.dao.AbstractDao;
import jp.agentec.abook.abv.bl.data.dao.AcmsDao;
import jp.agentec.abook.abv.bl.data.dao.MemberInfoDao;
import jp.agentec.abook.abv.bl.download.ContentRefresher;
import jp.agentec.abook.abv.bl.dto.BluetoothPairingDeviceInfoDto;
import jp.agentec.abook.abv.bl.dto.MemberInfoDto;
import jp.agentec.abook.abv.bl.dto.PasswordLockInfoDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.ContractLogic;
import jp.agentec.abook.abv.bl.logic.OperationLogic;
import jp.agentec.abook.abv.bl.logic.UserAuthenticateLogic;
import jp.agentec.abook.abv.bl.repo.RepoClient;
import jp.agentec.abook.abv.cl.environment.DeviceInfo;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVLoginActivity;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType.UserPrefKey;
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.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.helper.ABVViewUnbindHelper;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.adf.util.StringUtil;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.List;

/**
 * @author Minhyuk Seok
 * @editor Jang
 * @version 1.1.0
 */
public class LoginActivity extends ABVLoginActivity {
	private static final String TAG = "LoginActivity";

	private UserAuthenticateLogic userAuthenticateLogic;
	
	private MemberInfoDao memberInfoDao;
	private ContractLogic contractLogic;

	private String mSiteId;
	private String mUrlPath;
	private String mLoginId;
	private String mPassword;

	private EditText mEdtSiteId;
	private EditText mEdtUrlPath;
	private EditText mEdtLoginId;
	private EditText mEdtPassword;
	private TextView mTxtRequestLogin;
    private ImageButton mBtnDeviceInfo;

	private boolean mEdtUrlPathGoneFlg = false;
	private boolean mEdtLoginIdGoneFlg = false;
	private MemberInfoDto oldMemberInfoDto;

	private PasswordLockInfoDto passwordLockInfoDto;
	
	private InputMethodManager imm;

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

		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_login);

		contractLogic = AbstractLogic.getLogic(ContractLogic.class);
		userAuthenticateLogic = AbstractLogic.getLogic(UserAuthenticateLogic.class);
		memberInfoDao = AbstractDao.getDao(MemberInfoDao.class);

		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

		mEdtSiteId = (EditText) findViewById(R.id.edt_site_id);
		mEdtUrlPath = (EditText) findViewById(R.id.edt_url_path);
		mEdtLoginId = (EditText) findViewById(R.id.edt_id);
		mEdtPassword = (EditText) findViewById(R.id.edt_pwd);
		//ドトールの場合且つカスタムUriでログインする場合：ログイン画面が「ポータルにログインしてください」テキスト追加
		mTxtRequestLogin = (TextView)findViewById(R.id.login_label);
        mBtnDeviceInfo = (ImageButton) findViewById(R.id.btn_deviceId);
		mTxtRequestLogin.setVisibility(View.GONE);

		String urlPath;

		if (getRInteger(R.integer.login_mode) == LoginMode.ID_PASS) {
			// URLの入力が必要ない場合定数を入れる
			urlPath = getString(R.string.account_path);
		} else {
			urlPath = contractLogic.getUrlPath();
		}

		if (!StringUtil.isNullOrWhiteSpace(urlPath)) {
			mEdtUrlPath.setText(urlPath); // TODO: mUrlPathにセットすればいいのでは？
			mEdtUrlPath.setVisibility(View.GONE);
			mEdtUrlPathGoneFlg = true; // TODO:このフラグ必要？
		}
		if (getRInteger(R.integer.login_mode) == LoginMode.SITE_PATH_ID_PASS) {
			if (StringUtil.isNullOrWhiteSpace(ABVEnvironment.getInstance().acmsAddress)) { // urlPathとはセットで有無が合っている前提
				mEdtSiteId.setVisibility(View.VISIBLE);
			}
		}

		mEdtPassword.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
					tryLogin();
					return true;
				}
				return false;
			}
		});

		findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
				tryLogin();
			}
		});

        //androidバジョン6以上からMAC idではなくandroid固有numberを取得ため、ダイアログで表示
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            mBtnDeviceInfo.setVisibility(View.VISIBLE);
        } else {
            mBtnDeviceInfo.setVisibility(View.INVISIBLE);
        }
        mBtnDeviceInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ABookAlertDialog alert = AlertDialogUtil.createAlertDialog(LoginActivity.this,R.string.deviceId_title);
                alert.setMessage(ABVEnvironment.getInstance().deviceId);
                alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alert.dismiss();
                    }
                });
                alert.show();
            }});

		// 一定時間経過後、アプリロックか強制ログアウトの状態かチェックする
		oldMemberInfoDto = AbstractDao.getDao(MemberInfoDao.class).getMemberInfo();
		if (oldMemberInfoDto != null) {
			// ユーザが一定時間経過後アプリロックの状態であるかチェック
			if (oldMemberInfoDto.loginStatus == LoginStatus.LimitLogin.statusCode()) {
				mEdtLoginId.setText(oldMemberInfoDto.loginId);
				mEdtLoginId.setVisibility(View.GONE);
				ErrorMessage.showErrorMessageDialog(this, R.string.app_name, ErrorCode.L110);
				mEdtLoginIdGoneFlg = true;
			} else if (oldMemberInfoDto.loginStatus == LoginStatus.ForceLoggedOut.statusCode()) {
				// ユーザが一定時間経過後強制ログアウトの状態であるかチェック
				ErrorMessage.showErrorMessageDialog(this, R.string.app_name, ErrorCode.L110);
			}
		}
	}

	@Override
	public void onResume() {
		Logger.i(TAG, "onResume");
		super.onResume();
		ContentRefresher.getInstance().stopRefresh(); // 新着更新が走っている場合は停止する。
		getABVUIDataCache().isFirstLaunching = true;
		startLoadingAnimation();
	}

	@Override
	public void onStop() {
		super.onStop();
		ABVViewUnbindHelper.unbindReferences(getContentViewId());
	}

	@Override
    public void onPause() {
		super.onPause();
		finish();
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			imm.hideSoftInputFromWindow(mEdtLoginId.getWindowToken(), 0);
			if (mEdtPassword != null) {
				imm.hideSoftInputFromWindow(mEdtPassword.getWindowToken(), 0);
			}
			moveTaskToBack(true);
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected View getContentViewId() {
		return findViewById(R.id.linear_main);
	}

	private void startLoadingAnimation() {
		// アニメーション開始
		// ロゴの移動→入力欄の表示
		TranslateAnimation anim1 = new TranslateAnimation(0, 0, 100, 0);
		anim1.setDuration(1000);
		findViewById(R.id.img_logo).startAnimation(anim1);

		anim1.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				Logger.d(TAG, "onAnimationStart");
			}

			@Override
			public void onAnimationRepeat(Animation animation) {}

			@Override
			public void onAnimationEnd(Animation animation) {
				Logger.d(TAG, "onAnimationEnd");
				AlphaAnimation anim2 = new AlphaAnimation(0.0f, 1.0f);
				anim2.setDuration(2000);

				findViewById(R.id.login_panel).startAnimation(anim2);
				anim2.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {}

					@Override
					public void onAnimationRepeat(Animation animation) {}

					@Override
					public void onAnimationEnd(Animation animation) {
						findViewById(R.id.login_panel).setVisibility(View.VISIBLE);

						if (mEdtSiteId.getVisibility() == View.VISIBLE) {
							mEdtSiteId.requestFocus();
							imm.showSoftInput(mEdtSiteId, InputMethodManager.SHOW_IMPLICIT);
						}
						else if (!mEdtUrlPathGoneFlg) {
							mEdtUrlPath.requestFocus();
							imm.showSoftInput(mEdtUrlPath, InputMethodManager.SHOW_IMPLICIT);
						} else if (!mEdtLoginIdGoneFlg) {
							mEdtLoginId.requestFocus();
							imm.showSoftInput(mEdtLoginId, InputMethodManager.SHOW_IMPLICIT);
						} else {
							mEdtPassword.requestFocus();
							imm.showSoftInput(mEdtPassword, InputMethodManager.SHOW_IMPLICIT);
						}
					}
				});
			}
		});
	}

	/**
	 * ログイン開始
	 * @return
	 */
	private void tryLogin() {
		// 入力情報取得
		// スペースの文字列はreplaceするように修正
		if (mEdtSiteId.getVisibility() == View.VISIBLE) {
			mSiteId = mEdtSiteId.getText().toString().replaceAll(" ", "");;
		}
		mUrlPath = mEdtUrlPath.getText().toString().replaceAll(" ", "");
		mLoginId = mEdtLoginId.getText().toString().replaceAll(" ", "");
		mPassword = mEdtPassword.getText().toString();

		passwordLockInfoDto = userAuthenticateLogic.getPasswordLockInfoDto();
		// ログイン制限中の場合、メッセージを表示してログインさせない
		if (passwordLockInfoDto != null) {
			if (passwordLockInfoDto.passwordLockDate != null && userAuthenticateLogic.isPasswordLocked(passwordLockInfoDto.passwordLockDate)) {
				handleErrorMessageToast(ErrorCode.L117);
				return;
			}
		}

		if (validate()) {
			boolean agree_macInfor;
            agree_macInfor = getUserPref(UserPrefKey.AGREE_MACINFO, false);
			// Macアドレスに既に同意している場合、ログイン
			int deviceIdType = Constant.DeviceIdType.MAC_ADDRESS;
			try {
				 deviceIdType = DeviceInfo.getDeviceIdType(this , false);
			} catch (ABVException e) {
				// ここでは無視
			}

			if (agree_macInfor || deviceIdType  != Constant.DeviceIdType.MAC_ADDRESS) {
				threadLogin();
			} else {
				// マックアドレスの使用に関する同意文ダイアログ表示
				showPolicyInfoDialog();
			}
		}
	}

	
	/**
	 * 必須項目の入力チェック
	 * @return
	 */
	private boolean validate() {
		// キーボード非表示
		imm.hideSoftInputFromWindow(mEdtLoginId.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(mEdtPassword.getWindowToken(), 0);

		if (mEdtSiteId.getVisibility() == View.VISIBLE) {
			if (StringUtil.isNullOrWhiteSpace(mSiteId)) {
				handleErrorMessageToast(ErrorCode.E003);
				mEdtSiteId.requestFocus();
				return false;
			}
		}

		if (mEdtUrlPath.getVisibility() == View.VISIBLE) {
			if (StringUtil.isNullOrWhiteSpace(mUrlPath)) {
				handleErrorMessageToast(ErrorCode.E000);
				mEdtUrlPath.requestFocus();
				return false;
			}
		}
		return true;
	}

	/**
	 * MACアドレスの使用許可アラートを表示
	 */
	private void showPolicyInfoDialog() {
		ABookAlertDialog policyInfoDialog = AlertDialogUtil.createAlertDialog(this, R.string.app_name);
		policyInfoDialog.setMessage(R.string.abook_policy_information1);
		policyInfoDialog.setNegativeButton(R.string.disagree, null);
		policyInfoDialog.setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				putUserPref(UserPrefKey.AGREE_MACINFO, true);
				threadLogin();
			}
		});
		showAlertDialog(policyInfoDialog);
	}

	/**
	 * ログインスレッドの起動
	 */
	private void threadLogin() {
        if (!ABVEnvironment.getInstance().networkAdapter.isNetworkConnected()) {
            showSimpleAlertDialog(R.string.error, R.string.NETWORK);
            return;
        }

		try {
			loadWifiMacAddress(); // MACアドレスの取得
		} catch (ABVException e) { // 取得できない場合はエラーを表示し先には進まない
			Logger.e(TAG, "loadWifiMacAddress error. " + e.toString());
			showSimpleAlertDialog(R.string.error, R.string.C_E_SYSTEM_0004);
			return;
		}

		showProgressPopup();
		CommonExecutor.execute(new Runnable() {
			@Override
            public void run() {
				if (oldMemberInfoDto != null && oldMemberInfoDto.loginStatus == LoginStatus.LimitLogin.statusCode()) {
					// アプリロックの場合サーバ認証せずにログイン
					offlineLogin();
				} else {
					fcmRegister();
				}
			}
		});
	}

	/**
	 * サーバと通信せずにパスワードのチェックを行う。<br>
	 * 正しい場合、メイン画面を表示する。
	 */
	private void offlineLogin() {
		try {
			userAuthenticateLogic.offLineLogin(oldMemberInfoDto, mPassword);
			showMainActivity(mLoginId);
		} catch (ABVException e) {
			Logger.e("ABVException", e.toString());
			handingLoginABVException(e);
		} catch (Exception e) {
			Logger.e(TAG, "", e);
		}
		closeProgressPopup();
	}

	@Override
	protected void serverLoginAndCheckChangeUser(String deviceToken) {
		try {

			checkSiteId();
			if (ABVEnvironment.getInstance().acmsAddress == null) {
				return;
			}
			MemberInfoDto dto = userAuthenticateLogic.serverLogin(mUrlPath, mLoginId, mPassword, deviceToken);

			int deleteType = userAuthenticateLogic.isRequiredDeleteLocalData(dto);

            if (deleteType == DeleteDataType.None) {
                // ユーザ情報保存
                saveAndShowNextView(dto);
            } else {
                // 既存ユーザのデータ削除が必要な場合アラートを表示
                showChangeUserDialog(dto, deleteType);
            }
		} catch (NetworkDisconnectedException e) {
			Logger.e("NetworkDisconnectedException serverLoginAndCheckChangeUser ", e);
			String exceptionMessage = e.getMessage();
			if (exceptionMessage != null && exceptionMessage.equals(ExceptionDetailMessage.SERVER_IS_DISCONNECTED)) {
				handleErrorMessageToast(ErrorCode.L120);
			} else {
				handleErrorMessageToast(ErrorCode.NETWORK);
			}
		} catch (ABVException e) {
			Logger.e("ABVException", e.toString());
			handingLoginABVException(e);
		} catch (Exception e) {
			Logger.e(TAG, "", e);
		}
	}

	// サイトIDが入力されている場合レポジトリサーバに問い合わせる
	private void checkSiteId() {
		if (mSiteId != null) {
			try {
				CmsUrlJSON cmsUrlJSON = RepoClient.getInstance().getCmsUrl(getString(R.string.repository_fqdn), Integer.parseInt(mSiteId), mUrlPath);
				ABVEnvironment.getInstance().setAddress(cmsUrlJSON);
				
				Logger.i(TAG, "acmsAddress=%s,", ABVEnvironment.getInstance().acmsAddress);
				Logger.i(TAG, "downloadServerAddress=%s,", ABVEnvironment.getInstance().downloadServerAddress);
				Logger.i(TAG, "websocketServerHttpUrl=%s,", ABVEnvironment.getInstance().websocketServerHttpUrl);
				Logger.i(TAG, "websocketServerWsUrl=%s,", ABVEnvironment.getInstance().websocketServerWsUrl);
				return;
			} catch (AcmsException e) {
				handleErrorMessageToast(e.getMessage());
			} catch (NetworkDisconnectedException e) {
				handleErrorMessageToast(e);
			}
			// 例外が発生した場合、リセットしておく
			ABVEnvironment.getInstance().setAddress(null);
		}
	}

	private void handingLoginABVException(ABVException e) {
		if (e.getCode() == ABVExceptionCode.S_E_ACMS_L001) {
			if (passwordLockInfoDto != null) {
				boolean isCheckInvalidPasswardLimit = ABVEnvironment.getInstance().isCheckInvalidPasswordLimit;
				if (isCheckInvalidPasswardLimit) {
					passwordLockInfoDto.invalidPasswordCount++;	
				} else {
					passwordLockInfoDto.invalidPasswordCount = 0;
				}
				String msg;
				if (e.getCause() == null) {
					msg = ErrorMessage.getErrorMessage(this, e.getMessage());
				} else {
					msg = ErrorMessage.getErrorMessage(this, e.getCause());
				}

				if (isCheckInvalidPasswardLimit) {
					if (passwordLockInfoDto.invalidPasswordCount >= ABVEnvironment.InvalidPasswordLimit) {
						msg = msg + "\n" + ErrorMessage.getMessageByErrorCode(LoginActivity.this, ErrorCode.L117);
					} else {
						msg = msg + "\n" + String.format(ErrorMessage.getMessageByErrorCode(LoginActivity.this, ErrorCode.L118), ABVEnvironment.InvalidPasswordLimit - passwordLockInfoDto.invalidPasswordCount);
					}	
				}
				handleErrorMessageToast(msg);
			}
		} else if (e.getCode() == ABVExceptionCode.C_E_SECURITY_1001) {
			// response failed
			handleErrorMessageToast(ErrorMessage.getErrorCode(e));
		} else if (e.getCause() != null && e.getCause() instanceof AcmsException) {
			handleErrorMessageToast(ErrorMessage.getErrorMessage(this, e.getCause()));
		} else {
			handleErrorMessageToast(ErrorMessage.getErrorCode(e));
		}

	}
	
	/**
	 * ユーザ情報後、パスワード変更が必要な場合アラートを表示する。<br>
	 * 必要ない場合メイン画面を表示する。
	 * @param dto
	 */
	private void saveAndShowNextView(MemberInfoDto dto) {
		int changePasswordType = RequirePasswordChangeCode.getRequirePasswordChangeType(dto.requiredPasswordChange);
		
		// パスワード変更の状況に合わせてログインステータスの書き換え
		dto.loginStatus = userAuthenticateLogic.convertLoginStatusFromChangePasswordType(changePasswordType);
		userAuthenticateLogic.saveMemberInfo(dto, mUrlPath);

		if (changePasswordType == RequirePasswordChangeType.NONE) {
			// パスワード変更が必要ない場合、メイン画面表示
			showMainActivity(mLoginId);
		} else {
			// パスワード変更が必要な場合、アラート表示
			showChangePasswordDialog(changePasswordType);
		}
	}

	/**
	 * パスワード変更ダイアログの表示
	 * @param rpccType
	 */
	private void showChangePasswordDialog(final int rpccType) {
		String message = "";
		switch (rpccType) {
		case RequirePasswordChangeType.NEWLOGIN_REMINDER: //初回ログイン時の催促
			message = getResources().getString(R.string.pwd_change_newlogin_reminder_message);
			break;
		case RequirePasswordChangeType.REMINDER: //定期変更の催促
			message = getResources().getString(R.string.pwd_change_reminder_message);
			break;
		case RequirePasswordChangeType.NEWLOGIN_ENFORCEMENT: //初回ログイン時の強制
			message = getResources().getString(R.string.pwd_change_newlogin_enforcement_message);
			break;
		case RequirePasswordChangeType.REMINDER_ENFORCEMENT: ///定期変更時の強制
			message = getResources().getString(R.string.pwd_change_reminder_enforcement_message);
			break;
		}

		final String message_ = message;

		handler.post(new Runnable() {
			@Override
			public void run() {
				ABookAlertDialog changePwDialog = AlertDialogUtil.createAlertDialog(LoginActivity.this, R.string.pwd_change);
				changePwDialog.setMessage(message_);
				changePwDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					@Override
                    public void onClick(DialogInterface dialog, int whichButton) {
						if (rpccType == RequirePasswordChangeType.NEWLOGIN_REMINDER || rpccType == RequirePasswordChangeType.REMINDER) {
							// 催促の場合、キャンセルが押されたらメイン画面表示
							showMainActivity(mLoginId);
						}
					}
				});
				changePwDialog.setPositiveButton(R.string.pwd_change, new DialogInterface.OnClickListener() {
					@Override
                    public void onClick(DialogInterface dialog, int whichButton) {
						// パスワード変更画面表示
						Intent intent = new Intent();
						intent.putExtra("type", rpccType);
						intent.putExtra("loginId", mLoginId);
						intent.putExtra("password", mPassword);
						intent.setClassName(getApplicationContext().getPackageName(), LoginPasswordChangeActivity.class.getName()).setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						startActivity(intent);
						finish();
						dialog.dismiss();

					}
				});
				closeProgressPopup();
				showAlertDialog(changePwDialog);
			}
		});

	}
	/**
	 * ユーザ切替時のアラート表示
	 * @param dto
	 * @param deleteType
     */
	private void showChangeUserDialog(final MemberInfoDto dto, final int deleteType) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				ABookAlertDialog changeUserDialog = AlertDialogUtil.createAlertDialog(LoginActivity.this, R.string.change_user);

				if (DeleteDataType.All == deleteType) {
					changeUserDialog.setMessage(R.string.change_user_message);
				} else {
					changeUserDialog.setMessage(R.string.change_user_message2);
				}

				changeUserDialog.setNegativeButton(R.string.no, null);
				changeUserDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
					@Override
                    public void onClick(DialogInterface dialog, int whichButton) {
						if (mAlertDialog != null && mAlertDialog.isShowing()) {
							mAlertDialog.dismiss();
						}
						showProgressPopup();
						CommonExecutor.execute(new Runnable() {
							@Override
                            public void run() {
								Logger.i(TAG, "Try change user login");
								if (DeleteDataType.All == deleteType) {
									changeUserInit();
								} else {
									changeUserInit2();
								}
								//ユーザ変更があった場合、FetchDateをクリアする
								AcmsDao dao =  AbstractDao.getDao(AcmsDao.class);
								dao.clearFetchDate();
								saveAndShowNextView(dto);
								closeProgressPopup();
							}
						});
					}
				});
				closeProgressPopup();
				showAlertDialog(changeUserDialog);
			}
		});
	}

	/**
	 * ユーザ変更時の初期化
	 */
	private void changeUserInit() {
		// bluetoothの情報維持のため、PreferenceUtil初期化前にデータ取得（CHINO機器）
		List<BluetoothPairingDeviceInfoDto> bluetoothPairingInfoDtoList = getABVUIDataCache().getPairingBluetoothDeviceInfoList(Arrays.asList(DeviceType.centerThermomete, DeviceType.radiationThermomete));

		PreferenceUtil.clear(this);
		getABVUIDataCache().clear();
		PreferenceUtil.clearUserPref(this);
		memberInfoDao.deleteMemberInfo();

		//PreferenceUtil初期化後、ペアリングの情報保存（CHINO機器）
		for (BluetoothPairingDeviceInfoDto bluetoothPairingDeviceInfoDto : bluetoothPairingInfoDtoList) {
			getABVUIDataCache().setPairingBluetoothDeviceInfo(bluetoothPairingDeviceInfoDto);
		}

		contentLogic.deleteContentMarkingData();
		boolean isAllDelete =true;
		if (getRInteger(R.integer.not_delete_all_contents) == 1) {
			isAllDelete = false;
		} 
		contentLogic.deleteAllContent(isAllDelete);
		OperationLogic operationLogic = AbstractLogic.getLogic(OperationLogic.class);
		operationLogic.deleteAllOperation();
		memberInfoDao.deleteMemberContentInfo(isAllDelete);

		// MacAddress取得回答はOK済みと見なす
		Editor editor = PreferenceUtil.getUserEditor(this);
		editor.putBoolean(UserPrefKey.AGREE_MACINFO, true);
		editor.remove(UserPrefKey.SKEY);
		editor.remove(UserPrefKey.MEETING_ID);
		editor.remove(UserPrefKey.MEETING_PASSWORD);
		editor.remove(UserPrefKey.MEETING_ENTERED_FLG);
		editor.remove(UserPrefKey.MEETING_ENTERED_TIME);
		editor.commit();
	}
	/**
	 * ユーザ変更時の初期化(メモ・マーキング・しおり・閲覧履歴の削除)
	 */
	private void changeUserInit2() {
		memberInfoDao.deleteMemberInfo();
		contentLogic.deleteContentMarkingData();
		memberInfoDao.deleteMemberMydataInfo();
	}
	
	// Debug機能
	private int clickCount = 0;
	public void showAcmsAddress(View v) {
//		if (getResources().getInteger(R.integer.log_level) > 0) return; // 開発バージョンのみ対応
		clickCount++;
		if (clickCount >= 10) {
			Toast t = Toast.makeText(getApplicationContext(), getResources().getString(R.string.acms_address), Toast.LENGTH_LONG);
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
				t.setGravity(Gravity.TOP, 0, 0);
			}

			t.show();
			clickCount = 0;
		}
	}


	@Override
	protected void goNext() {
		showMainActivity(mLoginId);
	}
}
