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

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kr.co.zumo.app.lifeplus.bean.api.UserNoBean;
import kr.co.zumo.app.lifeplus.model.LifeplusPreferences;
import kr.co.zumo.app.lifeplus.model.SuperModel;
import kr.co.zumo.app.lifeplus.model.module.LoginModuleParser;
import kr.co.zumo.app.lifeplus.network.api.LifeplusAPIRepository;
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;

/**
 * ActivityStarter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018-09-29]   [최초 작성]
 * @since 2018-09-29
 */
public class ActivityStarter {
  private Context context;
  private Disposable disposable;

  public ActivityStarter(Context context) {
    this.context = context;
  }

  /**
   * 앱 부팅 상태에 따른 분기처리;
   *
   * @param isConnected
   */
  public void launch(boolean isConnected) {
    Log.i("APP# SplashActivity | onCreate", "| Network Connected ==============================================================> " + isConnected);
    LifeplusPreferences preferences = SuperModel.getInstance().getPreferences();

    Intent intent = null;
    if (isConnected == false) {
      intent = new Intent(context, NetworkErrorActivity.class);
    }
    else if (preferences.isPermissionInfoDone() == false) {
      intent = new Intent(context, PermissionInfoActivity.class);
    }
    else if (preferences.isTutorialDone() == false) {
      intent = new Intent(context, OnBoardingActivity.class);
    }
    else if (StringUtil.isEmpty(SuperModel.getInstance().getUserId())) {
      intent = new Intent(context, MainActivity.class);
    }
    else {
      /**
       * 로그인
       * 로그인 완료되면
       * -> 정상 : token 저장 > 메인화면
       * -> 비정상
       *   - 블럭 계정 > token 저장하지 않고 둠, 그러면 다시 로그인 시 블럭 계정
       *   - 휴면 계정 > 위와 같음
       *   - 일시 중지 > 위와 같음
       *
       */

      disposable = new LifeplusAPIRepository().selectMember(new UserNoBean(SuperModel.getInstance().getUserId()))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(loginResultBean -> {
          Log.i("APP# ActivityStarter | launch", "| loginResultBean: " + loginResultBean.toPrettyJson());
          if (new LoginModuleParser().parse(loginResultBean)) {
            // 정상 처리 됐음
            onLogin();
          }
          else {
            // 서버와 통신 완료 후 에러 리턴
            showErrorPopup("login error - " + loginResultBean.toJson());
          }
        }, e -> {
          // 서버와 통신이 되지 않은 에러
          showErrorPopup("login error - " + e.getLocalizedMessage());
        });

    }

    if (null != intent) {
      context.startActivity(intent);
    }
  }

  private void onLogin() {

    if (SuperModel.getInstance().isBlockMember()) {
      gotoScreen(BlockMemberActivity.class);
    }
    else if (SuperModel.getInstance().isRestMember()) {
      gotoScreen(RestMemberActivity.class);
    }
    else if (SuperModel.getInstance().isOutMember()) {
      showErrorPopup("탈퇴한 회원입니다.");
    }
    else {
      // 정상;
      gotoScreen(MainActivity.class);
    }
  }

  private DialogBase alertDialog;

  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) {
            gotoScreen(MainActivity.class);
          }
        }

        @Override
        public void onDialogCanceled(DialogBase dialog) {
          gotoScreen(MainActivity.class);
        }
      })
      .attribute((IAttribute<AlertDialog>) dialog -> {
        dialog.setText(errorMessage);
      })
      .show();
  }

  private void gotoScreen(Class className) {
    Intent intent = new Intent(context, className);
    context.startActivity(intent);
  }

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

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