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

import android.content.Context;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.application.App;
import kr.co.zumo.app.lifeplus.bean.MobileAuthBean;
import kr.co.zumo.app.lifeplus.bean.api.LifeplusAPIBean;
import kr.co.zumo.app.lifeplus.manager.ActionBarManager;
import kr.co.zumo.app.lifeplus.model.SignUpModel;
import kr.co.zumo.app.lifeplus.supervisor.ScreenID;
import kr.co.zumo.app.lifeplus.util.Formatter;
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.ISignUpView;
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;

/**
 * SignUpMobileAuthPresenter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 28.]   [최초 작성]
 * @since 2018. 9. 28.
 */
public class SignUpMobileAuthPresenter extends SignUpFragmentPresenter {
  private Disposable disposable;
  private DialogBase dialog;

  public SignUpMobileAuthPresenter(SignUpModel model, ISignUpView view) {
    super(model, view);
  }

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

  @Override
  protected void stopInternal() {
  }

  @Override
  protected void resumeInternal() {

  }

  @Override
  protected void pauseInternal() {

  }

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

  @Override
  public void onResult(Event event) {

  }

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

  @Override
  protected void onEventInternal(Event event) {
    switch (event.getEventId()) {
      case Event.CONFIRM:
        onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_PIN, ScreenID.DIRECTION_NEXT));
        break;
      case Event.SUCCESS:
        Log.i("APP# SignUpMobileAuthPresenter | onEventInternal", "|" + "resultString: " + event.getJson());
        onAuthResult(event);
        break;
      default:
        break;
    }
  }

  private void onAuthResult(Event event) {
    MobileAuthBean mobileAuthBean = event.fromJson(MobileAuthBean.class);
    LifeplusAPIBean resultBean = new Gson().fromJson(event.getString(), LifeplusAPIBean.class);

    Log.w("APP# SignUpMobileAuthPresenter | onEventInternal", "| 인증 결과: " + resultBean.toPrettyJson());
    Log.w("APP# SignUpMobileAuthPresenter | onEventInternal", "| 유저 데이터: " + mobileAuthBean.toPrettyJson());

    /**
     * 2. 성공 시 PROCESS 진입
     1) 만 14세 이상 : 약관동의(JO2001)화면 링크
     2) 14세 미만 : 14세 미만 가입불가 안내 (JO5002) 화면 링크
     3) 회원 Y: 기존회원 간편암호 확인 안내 (JO5002) 화면 링크 
     4) 회원탈퇴일 기준 30일 이내 Y
     - 탈퇴 회원 (30일 이내) 가입불가 안내 (JO5003) 화면 링크
     */
    if (resultBean.isSuccess()) {
      Context context = App.getInstance().getContext();
      Toast toast = new Toast(context);
      toast.setDuration(Toast.LENGTH_SHORT);
      toast.setGravity(Gravity.FILL, 0, 0);
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      View view = inflater.inflate(R.layout.sign_up_auth_result_dialog, null);
      ((TextView) view.findViewById(R.id.text_view_authorization_result_name)).setText(mobileAuthBean.getName());
      ((TextView) view.findViewById(R.id.text_view_authorization_result_gender)).setText(mobileAuthBean.getGender());
      ((TextView) view.findViewById(R.id.text_view_authorization_result_birth_date)).setText(
        Formatter.format(mobileAuthBean.getBirthDate(), MobileAuthBean.BIRTH_DATE_FORMAT, "yyyy.mm.dd")
      );
      String phoneNumber = mobileAuthBean.getFirstPhoneNumber() + mobileAuthBean.getPhoneNumber();
      Log.i("APP# SignUpMobileAuthPresenter | onAuthResult", "| b: " + phoneNumber);
      Log.i("APP# SignUpMobileAuthPresenter | onAuthResult", "| a: " + StringUtil.formatPhoneNumber(phoneNumber));
      ((TextView) view.findViewById(R.id.text_view_authorization_result_phone_number)).setText(
        StringUtil.formatPhoneNumber(phoneNumber)
      );
      toast.setView(view);
      toast.show();

      // 신규 가입
      model.setMobileAuthorizationBean(mobileAuthBean);
      model.checkMobileAuthorized();

      disposable = Completable.timer(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
        .subscribe(() -> {
          onEvent(new Event.Builder(Event.CONFIRM).build());
        }, Throwable::printStackTrace);
    }
    else if (resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_UNDER_14_YEARS) {
      //14세 미만
      onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_UNDER_14_YEARS, ScreenID.DIRECTION_NEXT));
    }
    else if (resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_ALREADY_MEMBER) {
      // 이미 회원
      onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_ALREADY_MEMBER, ScreenID.DIRECTION_NEXT));
    }
    else if (resultBean.getCode() == LifeplusAPIBean.RETURN_MOBILE_AUTH_ERROR_NEED_FOR_30_DAYS) {
      // 30일이내 가입
      onCommand(new FragmentChangeCommand(ScreenID.SIGN_UP_NEED_FOR_30DAYS, ScreenID.DIRECTION_NEXT));
    }
    else {
      // 알 수 없는 에러;
      dialog = 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) {
          }
        })
        .attribute((IAttribute<AlertDialog>) dialog -> {
          dialog.setText(ResourceUtil.getString(R.string.undefined_error));
        })
        .show();
    }
  }

  @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) {

  }
}
