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

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.model.SignUpModel;
import kr.co.zumo.app.lifeplus.supervisor.ScreenID;
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.command.FragmentChangeCommand;
import kr.co.zumo.app.lifeplus.view.presenter.Presenter;

/**
 * SignUpPinPresenter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 28.]   [최초 작성]
 * @since 2018. 9. 28.
 */
public class SignUpPinPresenter extends Presenter<SignUpModel, ISignUpPinView> {

  private String pin;
  private int matchCount;

  private CompositeDisposable disposable = new CompositeDisposable();

  public SignUpPinPresenter(SignUpModel model, ISignUpPinView view) {
    super(model, view);
  }

  @Override
  public void startInternal() {

  }

  @Override
  protected void stopInternal() {

  }

  @Override
  protected void resumeInternal() {

  }

  @Override
  protected void pauseInternal() {

  }

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

  @Override
  public void onResult(Event event) throws Throwable {

  }

  @Override
  public boolean onBackPressed() {
    onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_MOBILE_AUTHORIZATION, ScreenID.DIRECTION_BACK));
    return true;
  }

  @Override
  protected void onEventInternal(Event event) {
    switch (event.getEventId()) {
      case Event.SUCCESS:
        onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_AGREE, ScreenID.DIRECTION_NEXT));
        break;
      case Event.INIT:
        onPinStart();
        break;
      case Event.RESULT:
        onPinResult(event.getString());
        break;
      default:
        break;
    }
  }

  private void onPinResult(String result) {
    if (StringUtil.isFull(pin)) {
      // 두 번째 등록
      view.setDisabled();
      // 일치하는지 확인
      if (pin.length() == 4 && pin.equals(result)) {
        // 일치 하면 모델에 저장
        model.savePin(pin);
        onEvent(new Event.Builder(Event.SUCCESS).build());
      }
      else {
        // 일치 하지 않으면 5회 재시도 후
        if (++matchCount < 5) {
          view.updateGuideTextColor(ResourceUtil.getColor(R.color.CF12815));
          view.updateGuideText(String.format(ResourceUtil.getString(R.string.sign_up_register_pin_error), matchCount));
          view.updateTitleText(R.string.sign_up_register_pin_title);
          view.restart();
        }
        else {
          /*
           5회 이상 불일치 시 ‘간편암호가 5회이상 일치하지 않아, 입력값이 초기화됩니다.’ 밸리데이션 문구 1초간 노출
          - 입력값 초기화된 상태로 STEP1로 변경
           */
          view.updateGuideTextColor(ResourceUtil.getColor(R.color.CF12815));
          view.updateGuideText(R.string.sign_up_register_pin_init);
          view.updateTitleText(R.string.sign_up_register_pin_title);

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

              pin = null;

              onPinStart();
              view.restart();

            }, Throwable::printStackTrace)
          );
        }
      }
    }
    else {
      // 처음 입력;
      matchCount = 0;
      pin = result;
      view.setDisabled();
      view.updateGuideTextColor(ResourceUtil.getColor(R.color.C999999));
      view.updateGuideText(R.string.sign_up_register_pin_again);
      view.updateTitleText(R.string.sign_up_register_pin_title);
      view.restart();
    }
  }

  private void onPinStart() {
    view.setResetButtonVisible(false);
    view.updateGuideTextColor(ResourceUtil.getColor(R.color.C999999));
    view.updateGuideText(R.string.sign_up_register_pin);
    view.updateTitleText(R.string.sign_up_register_pin_title);
  }
}
