package tr.dhee.abox.demo.data;

import com.dhc.absdk.ABRet;
import com.dhc.absdk.ABSDK;
import tr.dhee.abox.demo.utils.AboxConstants;

import java.io.IOException;

/**
 * Class that handles socket device control via sockCtrl API.
 * Must be called after login (ABSDK already has the session).
 */
public class SwitchDataSource {

    public Result<String> sockCtrl(String soDevName, String status) {

        try {
            // 同步阻塞调用 SDK 的 sockCtrl 接口, 在 SwitchRepository 的后台线程执行
            ABRet abRet = ABSDK.getInstance().sockCtrl(soDevName, status);
            if (abRet != null && "00000".equals(abRet.getCode())) {
                // 成功: 返回状态描述
                String desc = "操作成功: " + status;
                return new Result.Success<>(desc);
            } else {
                // 失败: 映射返回码到中文提示, 并始终携带原始错误码
                String code = abRet != null ? abRet.getCode() : "unknown";
                String abMsg = abRet != null ? abRet.getMsg() : "";
                String mapped = AboxConstants.codeMap.get(code);
                String msg;
                if (mapped != null) {
                    msg = mapped + " (" + code + ")";
                } else if (abMsg != null && !abMsg.isEmpty()) {
                    msg = abMsg + " (" + code + ")";
                } else {
                    msg = "控制失败: " + code;
                }
                return new Result.Error(new IOException(msg));
            }
        } catch (Exception e) {
            // 网络异常 / SDK 异常等
            String detail = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
            return new Result.Error(new IOException("控制异常: " + detail, e));
        }
    }
}
