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

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.Log;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import kr.co.zumo.app.lifeplus.util.NetworkUtil;
import kr.co.zumo.app.lifeplus.util.StringUtil;

/**
 * NetworkReceiver
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 18.]   [최초 작성]
 * @since 2018. 9. 18.
 */
public class NetworkReceiver extends BroadcastReceiver {

  private Context context;
  private INetworkReceiverListener listener;

  NetworkReceiver(Context context, INetworkReceiverListener listener) {

    this.context = context;
    this.listener = listener;

    this.context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

  }

  /**
   * 네트워크 연결 상태를 알 수 있는 Observable 객체를 반환한다.
   *
   * @param context
   * @return rx Observable with Boolean
   */
  public static Observable<Boolean> getObservable(Context context) {
    return Observable.create((ObservableEmitter<Boolean> emitter) -> {
        NetworkReceiver networkReceiver = new NetworkReceiver(context, (isConnected, type) -> {
          if (emitter.isDisposed() == false) {
            emitter.onNext(isConnected);
          }
        });
        emitter.setCancellable(() -> networkReceiver.dispose());
      }
    );
  }

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = null;
    if (null != intent) {
      action = intent.getAction();
    }

    if (StringUtil.isFull(action) && ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
      NetworkStatus networkStatus = new NetworkStatus(NetworkUtil.getNetworkInfo(context));

      boolean isConnected = networkStatus.isConnected();

      Log.i("APP# NetworkReceiver | onReceive", "| networkStatus.isConnected(): " + isConnected);

      if (null != listener) {
        listener.onChangedConnection(isConnected, networkStatus.getConnectedType());
      }
    }
  }

  /**
   * dispose
   */
  public void dispose() {
    Log.i("APP# NetworkReceiver | dispose", "|");
    if (null != context) {
      context.unregisterReceiver(this);
      context = null;
    }
    listener = null;
  }

}
