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

import android.app.Activity;
import android.util.Log;

import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.model.PinModel;
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.PinDialog;
import kr.co.zumo.app.lifeplus.view.presenter.PinPresenter;

/**
 * PinDialogAgent
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018-09-23]   [최초 작성]
 * @since 2018-09-23
 */
public class PinDialogAgent implements IPinView {

  DialogBase dialog;
  PinPresenter presenter;
  Activity activity;

  public PinDialogAgent(Activity activity) {
    this.activity = activity;
    presenter = new PinPresenter(new PinModel(), this);
  }

  @Override
  public void dismissPinDialog() {
    if (null != dialog) {
      dialog.dismiss();
      dialog = null;
    }
  }

  @Override
  public void showPinDialog() {
    presenter.resetCounter();
    dialog = DialogBuilder.create(DialogID.INPUT_PIN)
      .attribute((IAttribute<PinDialog>) dialog -> {
        dialog.updateGuideText(R.string.login_input_pin);
        dialog.updateTitleText(R.string.login_input_pin_title);
      })
      .listener(new IDialogResultListener() {
        @Override
        public void onDialogResult(DialogBase dialog, Event event) {
          Log.i("APP# PinDialogAgent | onDialogResult", "|" + "resultCode: " + event.getEventId());
          if (Event.SUCCESS == event.getEventId()) {
            presenter.verifyPin(event.getString());
          }
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {

        }
      })
      .show();
  }

  @Override
  public void setEnabledPinDialog() {
    if (null != dialog) {
      dialog.setEnabled();
    }
  }

  @Override
  public void setDisabledPinDialog() {
    if (null != dialog) {
      dialog.setDisabled();
    }
  }

  @Override
  public void restartDialog() {
    if (null != dialog) {
      dialog.restart();
    }
  }

  @Override
  public void prepareDestroy() {
    if (null != dialog) {
      dialog.dismissAllowingStateLoss();
      dialog = null;
    }
    if (null != presenter) {
      presenter.dispose();
      presenter = null;
    }
    if (null != activity) {
      activity = null;
    }
  }

  @Override
  public Activity getActivity() {
    return activity;
  }
}
