package com.cmvr.test.flow.runtime.operator.edge;

import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.model.EdgeCommonVO;
import com.cmvr.edge.client.service.EdgeMicrophoneService;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class EdgeMicrophoneOperateService implements EdgeOperateService {

    private final EdgeMicrophoneService edgeMicrophoneService;

    @Override
    public boolean supports(ActionEnum action) {
        return action.name().startsWith("MICROPHONE_");
    }

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        String instId = message.getInstId();
        String nodeId = message.getNodeId();
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        String deviceId = inputParams.getString("deviceId");
        String terminalId = message.getTerminalId();

        JSONObject output = new JSONObject();
        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setDeviceId(deviceId);
        edgeCommonVO.setTerminalId(terminalId);
        switch (action) {
            case MICROPHONE_START: {
                String audioPath = edgeMicrophoneService.startRecord(edgeCommonVO);
                output.put("audioUrl", audioPath);
                break;
            }

            case MICROPHONE_STOP: {
                edgeMicrophoneService.stopRecord(edgeCommonVO);
                break;
            }

            default:
                throw new GlobalException("不支持的麦克风操作类型: " + action);
        }

        return TaskNodeExecuteResult.success(output);
    }
}
