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

import android.support.v7.app.ActionBar;

import java.util.List;

import io.reactivex.disposables.Disposable;
import kr.co.zumo.app.lifeplus.bean.api.PolicyBean;
import kr.co.zumo.app.lifeplus.manager.ActionBarManager;
import kr.co.zumo.app.lifeplus.model.SignUpModel;
import kr.co.zumo.app.lifeplus.model.SuperModel;
import kr.co.zumo.app.lifeplus.supervisor.ScreenID;
import kr.co.zumo.app.lifeplus.view.Event;
import kr.co.zumo.app.lifeplus.view.command.ActivityChangeCommand;
import kr.co.zumo.app.lifeplus.view.command.FragmentChangeCommand;
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;
import kr.co.zumo.app.lifeplus.view.presenter.Presenter;

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

  protected boolean isValidated = false;
  protected boolean isLoaded = false;
  protected boolean isSaved = false;
  protected boolean isViewReady = false;
  DialogBase alertDialog;
  Disposable disposable;

  public SignUpAgreePresenter(SignUpModel model, ISignUpAgreeView view) {
    super(model, view);

    this.model.requestPolicy();
  }

  @Override
  protected void startInternal() {
    ActionBarManager.getInstance().setProgress(75); // 270/360
  }

  @Override
  protected void stopInternal() {

  }

  @Override
  protected void resumeInternal() {

  }

  @Override
  protected void pauseInternal() {

  }

  @Override
  protected void destroyInternal() {
    model.stopPolicyRequest();

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

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

  @Override
  public void onResult(Event event) {
    switch (event.getEventId()) {
      case Event.RESULT:
        if (event.getInteger() == Event.POLICY_REQUEST) {
          isLoaded = true;
          renderAfterReady();
        }
        else if (event.getInteger() == Event.POLICY_CONFIRM) {
          // 약관 동의 전송 했음;
          isSaved = true;
          signUp();
        }
        else if (event.getInteger() == Event.MEMBER_JOIN) {
          login();
        }
        else if (event.getInteger() == Event.MEMBER_LOGIN) {
          onLogin();
        }
        break;
      case Event.ERROR:
        if (event.getInteger() == Event.POLICY_REQUEST) {
          showErrorPopup(event.getString());
        }
        else if (event.getInteger() == Event.POLICY_CONFIRM) {
          showErrorPopup(event.getString());
        }
        else if (event.getInteger() == Event.MEMBER_JOIN) {
          showErrorPopup(event.getString());
        }
        else if (event.getInteger() == Event.MEMBER_LOGIN) {
          showErrorPopup(event.getString());
        }
        break;
      default:
        break;
    }
  }

  private void login() {
    model.login();
  }

  private void onLogin() {

    if (SuperModel.getInstance().isBlockMember()) {
      onCommand(new ActivityChangeCommand(ScreenID.ACTIVITY_MEMBER_BLOCK, ScreenID.DIRECTION_NEXT));
    }
    else if (SuperModel.getInstance().isRestMember()) {
      onCommand(new ActivityChangeCommand(ScreenID.ACTIVITY_MEMBER_REST, ScreenID.DIRECTION_NEXT));
    }
    else if (SuperModel.getInstance().isOutMember()) {
      showErrorPopup("탈퇴한 회원입니다.");
    }
    else {
      // 정상
      onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_COMPLETED, ScreenID.DIRECTION_NEXT));
    }
  }

  private void showErrorPopup(String errorMessage) {

    alertDialog = 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) {
          dialog.dispose();
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(errorMessage);
      })
      .show();
  }

  private void renderAfterReady() {
    if (isLoaded && isViewReady) {
      view.init(getAgreeItems());
    }
  }

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

  @Override
  protected void onEventInternal(Event event) {
    switch (event.getEventId()) {
      case Event.SUCCESS:
        // 동의 버튼 눌렀음
        // 약관 동의 전송
        sendPolicyConfirm();
        break;
      case Event.CHANGED:
        onAgreeChanged();
        break;
      case Event.INIT:
        isViewReady = true;
        renderAfterReady();
        break;
      case Event.DETAIL:
        onClickDetail(event);
        break;
      default:
        break;
    }
  }

  private void sendPolicyConfirm() {
    if (isSaved) {
      signUp();
    }
    else {
      model.sendPolicy();
    }
  }

  private void onClickDetail(Event event) {
    String url = event.fromJson(PolicyBean.class).getUrl();
    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(url))
      .show();
  }

  private void onAgreeChanged() {

    validate();
    setButtonUsage();
  }

  /**
   * 약관 동의 데이터 bean 반환
   *
   * @return
   */
  private List<PolicyBean> getAgreeItems() {
    return model.getAgreeItems();
  }

  private void validate() {
    // SIGN_UP_AGREE 에서 이벤트로 변경 됨
    isValidated = model.isValidatedPolicy();
  }

  private void setButtonUsage() {
    view.setAgreeButtonEnabled(isValidated);
  }

  private void signUp() {
    /**
     * 회원 가입 절차 시작
     */

    model.signUp();
  }

  @Override
  public void onClickTitle(ActionBar actionBar) {

  }

  @Override
  public void onClickSearch(ActionBar actionBar) {

  }

  @Override
  public void onClickMenu(ActionBar actionBar) {

  }

  @Override
  public void onClickLike(ActionBar actionBar) {

  }

  @Override
  public void onClickBookmark(ActionBar actionBar) {

  }

  @Override
  public void onClickShare(ActionBar actionBar) {

  }
}
