/*
 * COPYRIGHT (c) 2018 All rights reserved by HANWHA LIFE.
 */
package kr.co.zumo.app.lifeplus.view.custom.pin;

import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.util.ResourceUtil;

/**
 * CustomPinConfirmPresenter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018-10-04]   [최초 작성]
 * @since 2018-10-04
 */
public class CustomPinConfirmPresenter implements IPinContract.Presenter {

  private IPinContract.View view;
  private IPinContract.Listener listener;

  private String pin;
  private int matchCount;
  private CompositeDisposable disposable = new CompositeDisposable();

  public CustomPinConfirmPresenter(IPinContract.View view, IPinContract.Listener listener) {
    this.view = view;
    this.listener = listener;

    this.view.setResetButtonVisible(true);
    this.view.setPresenter(this);
  }

  @Override
  public void onPinStart() {
    view.setResetButtonVisible(true);
    view.updateGuideTextColor(ResourceUtil.getColor(R.color.C999999));
    view.updateGuideText(R.string.login_input_pin);
    view.updateTitleText(R.string.login_input_pin_title);
    view.restart();
  }

  @Override
  public void onPinResult(String result) {
    view.setDisabled();
    listener.onPinResult(result);
  }

  @Override
  public void onClickPinReset() {
    listener.onClickPinReset();
  }

  @Override
  public void retry() {
    // 일치 하지 않으면 5회 재시도 후
    if (++matchCount < 5) {
      view.updateGuideTextColor(ResourceUtil.getColor(R.color.CF12815));
      view.updateGuideText(String.format(ResourceUtil.getString(R.string.pin_miss_match_error_repeat), matchCount));
      view.restart();
    }
    else {
          /*
           5회 이상 불일치 시 ‘간편암호가 5회이상 일치하지 않아, 입력값이 초기화됩니다.’ 밸리데이션 문구 1초간 노출
          - 입력값 초기화된 상태로 STEP1로 변경
           */
      view.updateGuideTextColor(ResourceUtil.getColor(R.color.CF12815));
      view.updateGuideText(R.string.pin_miss_match_error);

      view.setDisabled();
      disposable.add(
        Completable.timer(1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
          .subscribe(() -> {

            pin = null;
            listener.onPinFail();

          }, Throwable::printStackTrace)
      );
    }

  }

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