package xn.xxp.app;

import android.util.Log;

import androidx.annotation.WorkerThread;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import org.json.JSONObject;

import http.client.ApiRepository;
import http.client.HttpTool;
import http.vo.response.LaboratoryVo;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.Response;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.LabConfig;

public enum InitTool {
    INSTANCE;

    /**
     * 查询实验室配置
     */
    @WorkerThread
    public boolean queryLabConfig(String devID) {
        try {
            Response response = HttpTool.queryLabConfig(devID);
            if (response.isSuccessful()) {
                String json = response.body().string();
                LogUtils.d(json);
                JSONObject jsonObject = new JSONObject(json);
                int code = jsonObject.getInt("code");
                if (200 == code) {
                    LabConfig labConfig = GsonUtils.fromJson(jsonObject.getJSONObject("data").toString(), LabConfig.class);
                    RoomTool.getInstance().labConfigDao().clear();
                    RoomTool.getInstance().labConfigDao().insert(labConfig);
                    return true;
                } else {
                    ToastUtils.showLong(jsonObject.getString("message"));
                }
            }
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }

        return false;
    }

    /**
     * 查询实验室信息
     */
    @WorkerThread
    public Disposable queryLabInfo(String labId, androidx.core.util.Consumer<Boolean> consumer) {
        return ApiRepository.INSTANCE.laboratoryInfo(true, labId).subscribe(new Consumer<LaboratoryVo>() {
            @Override
            public void accept(LaboratoryVo laboratoryVo) throws Exception {
                LabApp.laboratory = laboratoryVo;
                if (null != consumer) {
                    consumer.accept(true);
                }
            }
        }, throwable -> {
            if (null != consumer) {
                consumer.accept(false);
            }
            LogUtils.e(Log.getStackTraceString(throwable));
            ToastUtils.showLong(throwable.getMessage());
        });
    }
}
