package cgmblelib.custom.livedata.connect;

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

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

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

    private static volatile OperationConnectLiveData sInstance;

    private OperationConnectBean mBean = new OperationConnectBean(EnumConnect.CONNECT_NONE);

    private OperationConnectListener mListener = (connect, glucosedId) -> {
        mBean.setConnect(connect);
        mBean.setGlucoseId(glucosedId);
        if (Tool.isInMainThread()) {
            setValue(mBean);
        } else {
            postValue(mBean);
        }
    };

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

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

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


    @Override
    protected void onActive() {
//        keyId = ManagementLiveData.getInstance().requestOperationConnectUpdate(mListener);
        ManagementLiveData.getInstance().requestOperationConnect(mListener);
    }

    @Override
    protected void onInactive() {
        ManagementLiveData.getInstance().removeOperationConnect();
    }


    public interface OperationConnectListener{
        void onChanged(EnumConnect connect, int glucosedId);
    }
}
