package kr.co.zumo.app.lifeplus.view.custom.auth;

import android.support.annotation.StringRes;
import android.util.Log;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.bean.MobileAuthBean;
import kr.co.zumo.app.lifeplus.bean.api.AuthConfirmRequestBean;
import kr.co.zumo.app.lifeplus.bean.api.AuthRequestBean;
import kr.co.zumo.app.lifeplus.bean.api.LifeplusAPIBean;
import kr.co.zumo.app.lifeplus.model.SuperModel;
import kr.co.zumo.app.lifeplus.network.api.LifeplusAPIRepository;
import kr.co.zumo.app.lifeplus.util.DateUtil;
import kr.co.zumo.app.lifeplus.util.Formatter;
import kr.co.zumo.app.lifeplus.util.ResourceUtil;
import kr.co.zumo.app.lifeplus.util.StringUtil;
import kr.co.zumo.app.lifeplus.view.Event;
import kr.co.zumo.app.lifeplus.view.dialog.AlertDialog;
import kr.co.zumo.app.lifeplus.view.dialog.DialogBase;
import kr.co.zumo.app.lifeplus.view.dialog.DialogBuilder;
import kr.co.zumo.app.lifeplus.view.dialog.DialogID;
import kr.co.zumo.app.lifeplus.view.dialog.IAttribute;
import kr.co.zumo.app.lifeplus.view.dialog.IDialogResultListener;
import kr.co.zumo.app.lifeplus.view.dialog.WebDialog;

/**
 * MobileAuthPresenter
 * <pre>
 * </pre>
 *
 * @author 하세미
 * @version 1.0
 * @history 하세미   [2018-09-14]   [최초 작성]
 * @since 2018-09-14
 */
public class MobileAuthPresenter implements IMobileAuthContract.Presenter {

  private CompositeDisposable disposable = new CompositeDisposable();
  private Disposable remainTimeDisposable;

  private MobileAuthBean userBean;
  private IMobileAuthContract.View view;
  private IMobileAuthContract.Listener listener;

  private String authorizationNumber;
  private DialogBase dialog;
  private int confirmRetryCount;
  private int timeExpansionCount;
  private int numberRequestingCount;

  public MobileAuthPresenter(IMobileAuthContract.View view, IMobileAuthContract.Listener listener) {
    this.view = view;
    this.listener = listener;

    this.view.setPresenter(this);

    // default setting
    userBean = new MobileAuthBean();
    userBean.setMobileCompany(ResourceUtil.getStringArray("mobile_companies")[0]);
    userBean.setFirstPhoneNumber(ResourceUtil.getStringArray("phone_numbers")[0]);
    userBean.setGender(MobileAuthBean.GENDER_MALE);
    userBean.setNationality(MobileAuthBean.NATIONALITY_DOMESTIC);

    resetInputAll();

  }

  public void dispose() {
    if (null != disposable) {
      disposable.dispose();
      disposable = null;
    }

    if (null != remainTimeDisposable) {
      remainTimeDisposable.dispose();
      remainTimeDisposable = null;
    }

    if (null != dialog) {
      dialog.dispose();
      dialog = null;
    }
  }

  private void doHideKeyBoard() {
    view.doHideKeyBoard();
  }

  /**
   * 레이아웃 터치 시
   */
  public void onClickLayout() {
    doHideKeyBoard();
  }

  /**
   * 동의하기 아코디언 구성
   */
  public void doAccordionAgreeList(boolean isVisible) {
    view.doAccordionAgreeList(isVisible);
  }

  /**
   * name 필드의 입력시 호출
   *
   * @param inputName
   */
  public void onNameTextChanged(String inputName) {
    Log.i("APP#  MobileAuthPresenter | doNameValidationMessage", "|" + inputName);

    userBean.setName(inputName);
    verifyName(userBean.getName(), true);
    verifyRequestNumberButton();
  }

  /**
   * 이름 입력 칸에 포커스 in/out
   *
   * @param isFocusChanged
   */
  public void onFocusNameText(boolean isFocusChanged) {
    if (isFocusChanged) {
      verifyName(userBean.getName(), true);
      verifyRequestNumberButton();
    }
    else {
      // 폰번호 입력 칸에 입력 중이라면 유효성 표시 남겨둠
      if (StringUtil.isEmpty(userBean.getPhoneNumber())) {
        view.doClearNameValidationTextView();
      }
    }
    Log.i("APP# MobileAuthPresenter | onFocusNameText", "|" + isFocusChanged);
  }

  /**
   * 생년월일 입력시 호출
   *
   * @param inputBirthDate
   */
  public void onBirthDateTextChanged(String inputBirthDate) {
    Log.i("APP#  MobileAuthPresenter | onBirthDateTextChanged", "|" + inputBirthDate);

    userBean.setBirthDate(inputBirthDate);
    verifyBirthDate(userBean.getBirthDate(), true);
    verifyRequestNumberButton();
  }

  /**
   * 생일 입력 칸에 포커스 in/out
   *
   * @param isFocusChanged
   */
  public void onFocusBirthDateText(boolean isFocusChanged) {
    if (isFocusChanged) {
      verifyBirthDate(userBean.getBirthDate(), true);
      verifyRequestNumberButton();
    }
    else {
      // 폰번호 입력 칸에 입력 중이라면 유효성 표시 남겨둠
      if (StringUtil.isEmpty(userBean.getPhoneNumber())) {
        view.doClearBirthDateValidationTextView();
      }
    }
  }

  /**
   * 휴대전화 뒤 7-8자리 입력시 호출
   *
   * @param phoneNumber
   */
  public void onPhoneNumberTextChanged(String phoneNumber) {
    Log.i("APP#  MobileAuthPresenter | onPhoneNumberCheckedValidationMessage", "|" + phoneNumber);

    userBean.setPhoneNumber(phoneNumber);
    verifyPhoneNumber(userBean.getPhoneNumber(), true);
    // 폰번호 입력 시에는 전체 전체 유효성 체크 표시
    verifyRequestNumberButton(true);
  }

  /**
   * 폰 번호 입력 칸에 포커스 in/out
   *
   * @param isFocusChanged
   */
  public void onFocusPhoneNumberText(boolean isFocusChanged) {
    if (isFocusChanged) {
      verifyPhoneNumber(userBean.getPhoneNumber(), true);
      // 포커싱 시 처음이면 무시하고, 내용이 있으면 전체 유효성 체크 표시
      verifyRequestNumberButton(StringUtil.isFull(userBean.getPhoneNumber()));
    }
    else {
      // 폰번호 입력 칸에 입력 중이라면 유효성 표시 남겨둠
      if (StringUtil.isEmpty(userBean.getPhoneNumber())) {
        view.doClearPhoneNumberValidationTextView();
      }
    }
  }

  /**
   * default 선택 값 남자의 체크유무 판별 후 성별 체크
   *
   * @param isMale
   */
  public void setOnGenderCheckedChanged(boolean isMale) {
    if (isMale) {
      userBean.setGender(MobileAuthBean.GENDER_MALE);
    }
    else {
      userBean.setGender(MobileAuthBean.GENDER_FEMALE);
    }
  }

  /**
   * default 선택 값 내국인의 체크유무 판별 후 국적 체크
   *
   * @param isLocal
   */
  public void onNationalCheckedChanged(boolean isLocal) {
    if (isLocal) {
      userBean.setNationality(MobileAuthBean.NATIONALITY_DOMESTIC);
    }
    else {
      userBean.setNationality(MobileAuthBean.NATIONALITY_FOREIGNER);
    }
  }

  /**
   * 핸드폰 번호 앞자리 spinner 선택시 호출
   *
   * @param firstPhoneNumber
   */
  public void onFirstPhoneNumberSelectChanged(String firstPhoneNumber) {
    Log.i("APP#  MobileAuthPresenter | onFirstPhoneNumberSelectChanged", "|" + firstPhoneNumber);
    userBean.setFirstPhoneNumber(firstPhoneNumber);
  }

  /**
   * 핸드폰 번호 앞자리 spinner 열림/닫힘
   *
   * @param isOpened
   */
  @Override
  public void onFirstPhoneNumberOpenChanged(boolean isOpened) {
    if (isOpened) {
      view.clearFocusAll();
    }
  }

  /**
   * 통신사 spinner 선택시 호출
   *
   * @param mobileCompany
   */
  public void onFirstMobileCompanySelectChanged(String mobileCompany) {
    userBean.setMobileCompany(mobileCompany);
  }

  /**
   * 핸드폰 번호 앞자리 spinner 열림/닫힘
   *
   * @param isOpened
   */
  @Override
  public void onFirstMobileCompanyOpenChanged(boolean isOpened) {
    if (isOpened) {
      view.clearFocusAll();
    }
  }

  /**
   * 전체동의 체크 버튼 클릭시 호출
   *
   * @param isChecked
   */
  public void onAllAgreeCheckedChanged(boolean isChecked) {
    doHideKeyBoard();
    verifyRequestNumberButton();
    view.clearFocusAll();
  }

  /**
   * 동의 체크
   *
   * @param index
   * @param isChecked
   */
  public void onAgreeCheckedChanged(int index, boolean isChecked) {
    userBean.setAgree(index, isChecked);
    verifyRequestNumberButton();
    view.clearFocusAll();
    Log.i("APP# MobileAuthPresenter | onAgreeCheckedChanged", "|" + userBean.getAgreeList().toString());
  }

  /**
   * 인증번호 입력 칸에 포커스
   *
   * @param isFocusChanged
   */
  public void onFocusValidationNumberText(boolean isFocusChanged) {
    if (isFocusChanged) {
      verifyAuthorizationNumber(authorizationNumber);
    }
    else {
      // 입력 칸에 입력 중이라면 유효성 표시 남겨둠
      if (StringUtil.isEmpty(authorizationNumber)) {
        view.doClearAuthorizedNumberValidationTextView();
      }
    }
  }

  /**
   * 인증번호 6자리 입력시 호출
   *
   * @param authorizedNumber
   */
  public void onAuthorizedNumberChanged(String authorizedNumber) {
    Log.i("APP#  MobileAuthPresenter | onPhoneNumberCheckedValidationMessage", "|" + authorizedNumber);
    verifyAuthorizationNumber(authorizedNumber);
    this.authorizationNumber = authorizedNumber;
  }

  /**
   * 인증 번호 확인 버튼 클릭
   */
  public void onAuthorizationConfirmButtonClick() {
    Log.i("APP#  MobileAuthPresenter | onAuthorizationConfirmButtonClick", "|" + "click");

    boolean isValidated = verifyAuthorizationNumber(this.authorizationNumber);

    if (isValidated) {
      // call api...
      doHideKeyBoard();
      view.setEnabledRequestConfirmButton(false);

      AuthConfirmRequestBean bean = new AuthConfirmRequestBean();
      bean.setPhoneNumber(userBean.getFirstPhoneNumber() + userBean.getPhoneNumber());
      bean.setAuthorizationNumber(this.authorizationNumber);

      disposable.add(
        new LifeplusAPIRepository().confirmMobileAuth(bean)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(resultBean -> {
            Log.i("APP# MobileAuthPresenter | onAuthorizationConfirmButtonClick", "|" + resultBean.toPrettyJson());
            if (resultBean.isSuccess()
              || resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_NEED_FOR_30_DAYS
              || resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_UNDER_14_YEARS
              || resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_ALREADY_MEMBER
              ) {
              // 성공
              doSomeWhenConfirmSuccess(resultBean);
            }
            else {
              // 실패
              countFailWithPopup();
            }
          }, e -> {
            // 실패
            countFailWithPopup();
          })
      );
    }
    else {
      showInvalidateConfirmPopup(R.string.phone_identify_number_need);
    }
  }

  private void countFailWithPopup() {
    // 1,2 회 팝업 "phone_identify_number_fail_1"
    // 3 회 "phone_identify_number_fail_2"
    if (++confirmRetryCount > 2) {
      // 3회
      showFailPopup(R.string.phone_identify_number_fail_2, new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          if (event.getEventId() == Event.CONFIRM) {
            dialog.dispose();
          }
          resetInputAll();
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
          resetInputAll();
        }
      });
    }
    else {
      // 1, 2 회
      showFailPopup(R.string.phone_identify_number_fail_1, new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          if (event.getEventId() == Event.CONFIRM) {
            dialog.dispose();
          }
          view.setEnabledRequestConfirmButton(true);
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
          view.setEnabledRequestConfirmButton(true);
        }
      });
    }
  }

  private void resetInputAll() {
    confirmRetryCount = 0;
//    view.setEnabledRequestNumberButton(false);
    view.setEnabledRequestConfirmTextView(false);
    view.setEnabledRequestConfirmButton(false);
    view.doClearRequestConfirmTextView();
    view.doClearAuthorizedNumberValidationTextView();
    view.showRemainTime(false);
    view.renderRemainTime("");
    disposeRemainRendering();
    disposable.clear();

    verifyRequestNumberButton();
  }

  private void prepareConfirm() {
    confirmRetryCount = 0;
  }

  private void showFailPopup(@StringRes int stringId, IDialogResultListener listener) {
    dialog = DialogBuilder.create(DialogID.ALERT)
      .listener(listener)
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(ResourceUtil.getString(stringId));
      })
      .show();
  }

  private void doSomeWhenConfirmSuccess(LifeplusAPIBean bean) {
    Log.i("APP# MobileAuthPresenter | doSomeWhenConfirmSuccess", "|" + bean.toPrettyJson());

    view.setEnabledExpansionTimeButton(false);
    view.setEnabledRequestNumberButton(false);
    view.setEnabledRequestConfirmTextView(false);
    view.setEnabledRequestConfirmButton(false);
    view.clearFocusAll();
    view.setDisabledAll();

    listener.onAuthResult(new Event.Builder(Event.SUCCESS).string(bean.toJson()).json(userBean.toJson()).build());
  }

  private void showInvalidateConfirmPopup(@StringRes int stringId) {
    dialog = DialogBuilder.create(DialogID.ALERT)
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          if (event.getEventId() == Event.CONFIRM) {
            dialog.dispose();
          }
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(ResourceUtil.getString(stringId));
      })
      .show();
  }

  private void verifyRequestNumberButton() {
    verifyRequestNumberButton(false);
  }

  private void verifyRequestNumberButton(boolean isDisplay) {
    boolean isValidated = verifyRequestNumberValidation(isDisplay);
    view.setEnabledRequestNumberButton(isValidated);
  }

  private boolean verifyRequestNumberValidation(boolean isDisplay) {
    boolean isValidated = true;
    if (verifyName(userBean.getName(), isDisplay) == false) {
      isValidated = false;
    }

    if (verifyBirthDate(userBean.getBirthDate(), isDisplay) == false) {
      isValidated = false;
    }

    if (verifyPhoneNumber(userBean.getPhoneNumber(), isDisplay) == false) {
      isValidated = false;
    }

    if (verifyAgrees(userBean.getAgreeList()) == false) {
      isValidated = false;
    }

    return isValidated;
  }

  /**
   * 인증번호 발송 버튼 클릭, 인증 번호 발송 전 user 정보 data 준비.
   */
  public void onAuthorizationNumberSendButtonClick() {
    Log.i("APP#  MobileAuthPresenter | onAuthorizationNumberSendButtonClick", "|" + userBean.toPrettyJson());

    /**
     * 유효성 체크
     * - 실패 시 해당 위치로 이동
     * - 통과하면 api 호출
     */

    boolean isValidated = verifyRequestNumberValidation(true);

    if (isValidated) {
      // call api...
      Log.w("APP# MobileAuthPresenter | onAuthorizationNumberSendButtonClick", "|" + "call api ============ ");

      prepareConfirm();

      doHideKeyBoard();
      view.setEnabledRequestNumberButton(false);

      AuthRequestBean bean = new AuthRequestBean();
      bean.setName(userBean.getName());
      bean.setGender(userBean.getGender());
      bean.setNationality(userBean.getNationality());
      bean.setPhoneNumber(userBean.getFullPhoneNumber());
      bean.setBirthDate(userBean.getBirthDate());
      bean.setDeviceUuid(SuperModel.getInstance().getDeviceUuid());
      bean.setMobileCompany(userBean.getMobileCompany());

      disposable.add(
        new LifeplusAPIRepository().requestMobileAuth(bean)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(resultBean -> {
            Log.i("APP# MobileAuthPresenter | onAuthorizationNumberSendButtonClick", "|" + resultBean.toPrettyJson());
            // todo 결과 비교해서 성공/실패 처리
            if (resultBean.isSuccess()) {
              // 성공
              doSomeWhenSendingSuccess();
            }
            else {
              // 실패
              doSomeWhenSendingFail();
            }
          }, e -> {
            doSomeWhenSendingFail();
          })
      );
    }
  }

  private void doSomeWhenSendingFail() {
    view.setEnabledRequestNumberButton(true);
    view.setEnabledRequestConfirmTextView(false);
    view.setEnabledRequestConfirmButton(false);
    showSendingPopup(R.string.phone_identify_submit_message_fail);
  }

  private void doSomeWhenSendingSuccess() {
    setEnabledConfirmView(true);
    timeExpansionCount = 0;
    countRemainTime();

    numberRequestingCount++;
    countRetryButton();

  }

  private void setEnabledConfirmView(boolean isEnabled) {
    view.setEnabledRequestConfirmTextView(isEnabled);
    view.showRemainTime(isEnabled);
    view.setEnabledExpansionTimeButton(isEnabled);

    if(false == isEnabled) {
      disposeRemainRendering();
    }
  }

  /**
   * 인증번호 시간 지연 버튼 클릭
   */
  public void onAuthorizationTimeExpansionButtonClick() {
    if (timeExpansionCount++ == 0) {
      countRemainTime();
      view.setEnabledExpansionTimeButton(false);
    }
  }

  private void countRemainTime() {
    disposeRemainRendering();
    remainTimeDisposable =
      Observable.interval(0, 1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
        .take(181)  // 3분
        .subscribe(
          (Long tick) -> {
            view.renderRemainTime(Formatter.format((180 - tick) * 1000, "mm:ss"));
          }
          , Throwable::printStackTrace,
          () -> {
            view.renderRemainTime("");
            setEnabledConfirmView(true);
            showTimeOverPopup(R.string.phone_identify_input_time_over);
          }
        );
  }

  private void showTimeOverPopup(@StringRes int stringId) {
    dialog = DialogBuilder.create(DialogID.ALERT)
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          if (event.getEventId() == Event.CONFIRM) {
            dialog.dispose();
          }
          resetInputAll();
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
          resetInputAll();
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(ResourceUtil.getString(stringId));
      })
      .show();
  }

  private void disposeRemainRendering() {
    if (null != remainTimeDisposable) {
      remainTimeDisposable.dispose();
      remainTimeDisposable = null;
    }
  }

  private void showSendingPopup(@StringRes int stringId) {
    dialog = DialogBuilder.create(DialogID.ALERT)
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          if (event.getEventId() == Event.CONFIRM) {
            dialog.dispose();
          }
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(ResourceUtil.getString(stringId));
      })
      .show();
  }

  private void countRetryButton() {
    int takingNumber = 11;
    if (numberRequestingCount > 3) {
      takingNumber = 61;

      // 3회 재시도 시 인증번호 입력 칸 보이지 않게 수정;
      setEnabledConfirmView(false);
    }

    int finalTakingNumber = takingNumber;
    disposable.add(
      Observable.interval(0, 1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
        .take(takingNumber)
        .subscribe(
          (Long tick) -> {
            view.renderRetryButton(String.format("%s %s", ResourceUtil.getString(R.string.phone_identify_submit_retry), Formatter.format((finalTakingNumber - 1 - (int) (long) tick) * 1000, "mm:ss")));
          }
          , Throwable::printStackTrace,
          () -> {

            if (numberRequestingCount > 3) {
              numberRequestingCount = 0;
            }
            view.setEnabledRequestNumberButton(true);
            view.renderRetryButton(ResourceUtil.getString(R.string.phone_identify_submit_retry));
          }
        )
    );
  }

  /**
   * 동의 세부 정보 보기 눌렀을 때
   *
   * @param index
   */
  public void onClickAgreeDetail(int index) {
    // todo index 에 따른 디테일 화면 웹뷰 표시
    dialog = DialogBuilder.create(DialogID.WEB)
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {

        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {

        }
      })
      .attribute((IAttribute<WebDialog>) d -> d.setUrl("https://google.com/" + index))
      .show();
  }

  /***********************************
   * Validation - after request Number
   ***********************************/

  private boolean verifyAuthorizationNumber(String authorizationNumber) {

    boolean result = false;

    if (StringUtil.isEmpty(authorizationNumber)) {
      authorizationNumber = "";
    }

    authorizationNumber = StringUtil.getPureNumber(authorizationNumber);

    if (authorizationNumber.length() == 0) {
      view.doAuthorizedNumberValidationMessage(R.string.phone_identify_six_characters);
    }
    else if (authorizationNumber.length() <= 5) {
      view.doAuthorizedNumberValidationMessage(R.string.phone_identify_number_validation_message);
    }
    else {
      view.doClearAuthorizedNumberValidationTextView();
      result = true;
    }

    view.setEnabledRequestConfirmButton(result);

    return result;
  }


  /***********************************
   * Validation - before request Number
   ***********************************/

  private boolean verifyAgrees(List<Boolean> list) {
    boolean result = true;

    for (Boolean aBoolean : list) {
      result &= aBoolean;
    }

    return result;
  }

  private boolean verifyPhoneNumber(String phoneNumber, boolean isDisplay) {
    boolean result = false;

    if (StringUtil.isEmpty(phoneNumber)) {
      phoneNumber = "";
    }

    phoneNumber = StringUtil.getPureNumber(phoneNumber);

    if (phoneNumber.length() == 0) {
      if (isDisplay) {
        view.doPhoneNumberCheckedValidationMessage(R.string.phone_identify_phone_validation);
      }
    }
    else if (phoneNumber.length() <= 6) {
      if (isDisplay) {
        view.doPhoneNumberCheckedValidationMessage(R.string.phone_identify_phone_validation);
      }
    }
    else {
      if (isDisplay) {
        view.doClearPhoneNumberValidationTextView();
      }
      result = true;
    }

    return result;
  }

  private boolean verifyBirthDate(String birthDate, boolean isDisplay) {
    boolean result = false;

    if (StringUtil.isEmpty(birthDate)) {
      birthDate = "";
    }

    birthDate = StringUtil.getPureNumber(birthDate);

    if (birthDate.length() == 0) {
      Log.i("APP# MobileAuthPresenter | verifyBirthDate", "|" + "length 0");
      if (isDisplay) {
        view.doBirthDateValidationMessage(R.string.phone_identify_birth_date_input_validation_message);
      }
    }
    else if (
      birthDate.length() <= 7
        || birthDate.matches("^[012].+") == false
      ) {
      //숫자 7자리 이하 입력시, or YYYY 으로 시작 하지 않았을 경우;
      Log.i("APP# MobileAuthPresenter | verifyBirthDate", "|" + "birthDateLength check");
      if (isDisplay) {
        view.doBirthDateValidationMessage(R.string.phone_identify_birth_date_length_validation_message);
      }
    }
    else if (birthDate.length() == 8) { //8자리 확인
      if (isDisplay) {
        view.doClearBirthDateValidationTextView();
      }
      // 년 월 일 확인
      int year = Integer.valueOf(birthDate.substring(0, 4));
      int month = Integer.valueOf(birthDate.substring(4, 6));
      int date = Integer.valueOf(birthDate.substring(6, 8));

      if (year > 0 && month <= 12 && month > 0 && date <= 31 && date > 0) {
        Log.i("APP# MobileAuthPresenter | verifyBirthDate", "|" + year + " " + month + " " + date);

        Calendar birthday = Calendar.getInstance();
        birthday.set(year, month - 1, date);
        boolean isOverAge = DateUtil.minAge(14, birthday.getTimeInMillis());

        Log.i("APP# MobileAuthPresenter | verifyBirthDate", "| isOverAge: " + isOverAge);

        if (isOverAge) {
          // 14 세 이상 가입 가능
          result = true;
        }
        else {
          // 14 세 미만 가입 불가 알림
          Log.i("APP# MobileAuthPresenter | onBirthDateTextChanged", "|" + "14세미만 알림");
          if (isDisplay) {
            view.doBirthDateValidationMessage(R.string.phone_identify_age_limit_validation_message);
          }
        }
      }
      else {
        if (isDisplay) {
          view.doBirthDateValidationMessage(R.string.phone_identify_birth_date_length_validation_message);
        }
      }
    }

    return result;
  }

  private boolean verifyName(String inputName, boolean isDisplay) {
    boolean result = false;

    if (StringUtil.isEmpty(inputName)) {
      inputName = "";
    }

    if (inputName.length() == 0) {
      //이름 미입력시
      if (isDisplay) {
        view.doNameValidationMessage(R.string.phone_identify_name_input_validation);
      }
    }
    else if (inputName.length() <= 1) {
      //한글 2자 미만 입력시
      if (isDisplay) {
        view.doNameValidationMessage(R.string.phone_identify_name_length_validation);
      }
    }
    else {
      if (isDisplay) {
        view.doClearNameValidationTextView();
      }
      result = true;
    }

    return result;

  }

}
