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

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.application.App;
import kr.co.zumo.app.lifeplus.model.NetworkErrorModel;
import kr.co.zumo.app.lifeplus.network.NetworkWatcher;
import kr.co.zumo.app.lifeplus.supervisor.ScreenID;
import kr.co.zumo.app.lifeplus.view.Event;
import kr.co.zumo.app.lifeplus.view.INetworkErrorView;
import kr.co.zumo.app.lifeplus.view.command.ActivityChangeCommand;
import kr.co.zumo.app.lifeplus.view.command.ExitCommand;

/**
 * NetworkErrorPresenter
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 21.]   [최초 작성]
 * @since 2018. 9. 21.
 */
public class NetworkErrorPresenter extends Presenter<NetworkErrorModel, INetworkErrorView> {

  Disposable disposable;

  public NetworkErrorPresenter(NetworkErrorModel model, INetworkErrorView view) {
    super(model, view);
  }

  @Override
  public void start() {

  }

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

  @Override
  public boolean onBackPressed() {
    onCommand(new ExitCommand());
    return true;
  }

  @Override
  protected void performOnEvent(Event event) {
    switch (event.getEventId()) {
      case Event.RETRY:
        retry();
        break;
      default:
        break;
    }
  }

  private void retry() {
    /**
     * 네트워크 연결 다시 시도
     * - 연결됐다면 메인으로 이동
     */
    disposable = NetworkWatcher.check(App.getInstance().getContext())
      .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
      .subscribe(isConnected -> {
      Log.i("APP# NetworkDisconnectedFragmentPresenter | checkNetworkConnection", "| isConnected: " + isConnected);
      if (isConnected) {
        // 메인으로 이동
        onCommand(new ActivityChangeCommand(ScreenID.ACTIVITY_MAIN, ScreenID.DIRECTION_NEXT));
      }
      else {
        // 그냥 그대로 있음;
      }
    }, Throwable::printStackTrace);
  }

  /***********************************
   * listener
   ***********************************/
  @Override
  public void onChangedConnection(boolean isConnected, int type) {
    Log.i("APP# Presenter | onChangedConnection", "| " + this.getClass().getSimpleName() + ", isConnected:" + isConnected);

    if (true == isConnected) {
      onCommand(new ActivityChangeCommand(ScreenID.ACTIVITY_MAIN, ScreenID.DIRECTION_NEXT));
    }
  }
}
