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

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.device.service.InspectionAlertListenService;
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.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 巡检报警监听工作流组件。
 */
@Service
@RequiredArgsConstructor
public class EdgeInspectionAlertOperateService implements EdgeOperateService
{
    private final InspectionAlertListenService inspectionAlertListenService;

    @Override
    public boolean supports(ActionEnum action)
    {
        return ActionEnum.INSPECTION_ALERT_LISTEN_START.equals(action)
                || ActionEnum.INSPECTION_ALERT_LISTEN_STOP.equals(action);
    }

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message)
    {
        JSONObject inputParams = message.getInputParams() == null ? new JSONObject() : message.getInputParams();
        String terminalId = StringUtils.defaultIfBlank(inputParams.getString("terminalId"), message.getTerminalId());
        Collection<String> eventTypes = resolveEventTypes(inputParams);
        String listenerKey = inputParams.getString("listenerKey");

        InspectionAlertListenService.ListenState state;
        switch (message.getAction())
        {
            case INSPECTION_ALERT_LISTEN_START:
                state = inspectionAlertListenService.startListen(terminalId, eventTypes,
                        message.getInstId(), message.getTaskId(), message.getItemId(),
                        message.getNodeId(), listenerKey);
                break;
            case INSPECTION_ALERT_LISTEN_STOP:
                state = inspectionAlertListenService.stopListen(terminalId, eventTypes,
                        message.getInstId(), message.getItemId(), listenerKey);
                break;
            default:
                throw new GlobalException("不支持的巡检报警监听动作: " + message.getAction());
        }

        JSONObject output = new JSONObject();
        output.put("terminalId", state.getTerminalId());
        output.put("grpcIp", state.getGrpcIp());
        output.put("eventTypes", state.getEventTypes());
        return TaskNodeExecuteResult.success(output);
    }

    private Collection<String> resolveEventTypes(JSONObject inputParams)
    {
        List<String> eventTypes = new ArrayList<>();

        Object rawEventTypes = inputParams.get("eventTypes");
        if (rawEventTypes instanceof JSONArray)
        {
            JSONArray array = (JSONArray) rawEventTypes;
            for (int i = 0; i < array.size(); i++)
            {
                eventTypes.add(array.getString(i));
            }
        }
        else if (rawEventTypes instanceof Collection)
        {
            for (Object item : (Collection<?>) rawEventTypes)
            {
                if (item != null)
                {
                    eventTypes.add(String.valueOf(item));
                }
            }
        }
        else if (rawEventTypes != null)
        {
            addDelimited(eventTypes, String.valueOf(rawEventTypes));
        }

        addDelimited(eventTypes, inputParams.getString("eventType"));
        return eventTypes;
    }

    private void addDelimited(List<String> eventTypes, String value)
    {
        if (StringUtils.isBlank(value))
        {
            return;
        }
        String[] split = value.split(",");
        for (String item : split)
        {
            eventTypes.add(StringUtils.trim(item));
        }
    }
}
