package tr.dhee.abox.demo.ui.switchcontrol;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import tr.dhee.abox.demo.data.Result;
import tr.dhee.abox.demo.data.SwitchRepository;

public class SwitchViewModel extends ViewModel {

    private final MutableLiveData<SwitchResult> switchResult = new MutableLiveData<>();
    private final SwitchRepository switchRepository;

    SwitchViewModel(SwitchRepository switchRepository) {
        this.switchRepository = switchRepository;
    }

    LiveData<SwitchResult> getSwitchResult() {
        return switchResult;
    }

    /**
     * 控制插座开关
     *
     * @param soDevName 插座设备名称
     * @param status    状态: "1"(开) 或 "0"(关)
     */
    public void controlSwitch(String soDevName, String status) {
        switchRepository.sockCtrl(soDevName, status, result -> {
            if (result instanceof Result.Success) {
                String data = ((Result.Success<String>) result).getData();
                switchResult.postValue(new SwitchResult(data, null));
            } else {
                Exception err = ((Result.Error) result).getError();
                switchResult.postValue(new SwitchResult(null,
                        err != null ? err.getMessage() : "控制失败"));
            }
        });
    }
}
