package cgmblelib.custom.livedata.scan;

import androidx.annotation.MainThread;
import androidx.lifecycle.LiveData;

import cgmblelib.custom.livedata.ManagementLiveData;
import cgmblelib.utils.MyLog;
import cgmblelib.utils.Tool;

/**
 * Created by minyuchun on 2019/10/23.
 * 用户在Service中获取设备信息变化
 * @author minyuchun
 */
public class OperationScanLiveData extends LiveData<OperationScanBean> {

    private static volatile OperationScanLiveData sInstance;

    private OperationScanBean mBean = new OperationScanBean(EnumScan.SCAN_NONE);

    private OperationScanListener mListener = (scan, device) -> {
        mBean.setScan(scan);
       // mBean.setDevice(device);
        mBean.setDeviceAndRssi(device);
        if (Tool.isInMainThread()) {
            setValue(mBean);
        } else {
            postValue(mBean);
        }
    };

    public OperationScanLiveData() {
        if (Tool.isInMainThread()) {
            setValue(mBean);
        } else {
            postValue(mBean);
        }
    }

    public void setListener(OperationScanListener listener) {
        mListener = listener;
    }

    @MainThread
    public static OperationScanLiveData get() {
        if (sInstance == null) {
            sInstance = new OperationScanLiveData();
        }
        return sInstance;
    }


    @Override
    protected void onActive() {
//        MyLog.i("onActive");
        ManagementLiveData.getInstance().requestOperationScan(mListener);
    }

    @Override
    protected void onInactive() {
        MyLog.i("onInactive");
        ManagementLiveData.getInstance().removeOperationScan();
    }


    public interface OperationScanListener{
        void onChanged(EnumScan scan, PocDeviceAndRssi deviceAndRssi);
    }
}
