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

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.model.arm.EdgeArmMoveJVO;
import com.cmvr.edge.client.service.EdgeArmService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;


@Slf4j
@Service
@RequiredArgsConstructor
public class EdgeTouchOperateService implements EdgeOperateService {

    private final EdgeArmService edgeArmService;

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

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

        if (Objects.requireNonNull(action) == ActionEnum.TOUCH) {
            EdgeArmMoveJVO edgeArmMoveJVO = JSON.parseObject(touchParams, EdgeArmMoveJVO.class);
            edgeArmMoveJVO.setTerminalId(terminalId);
            edgeArmMoveJVO.setDeviceId(deviceId);

            edgeArmService.moveJ(
                    edgeArmMoveJVO,
                    edgeArmMoveJVO.getTarget(),
                    edgeArmMoveJVO.getVelocity(),
                    edgeArmMoveJVO.getAcceleration(),
                    edgeArmMoveJVO.getBlendRadius(),
                    edgeArmMoveJVO.getJointVelocityLimits(),
                    edgeArmMoveJVO.getAsynchronous()
            );
        } else {
            throw new GlobalException("不支持的触控操作类型: " + action);
        }
        return TaskNodeExecuteResult.success();
    }

}
