package io.wdd.agent.config.message.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.wdd.agent.executor.CommandExecutor;
import io.wdd.agent.executor.FunctionExecutor;
import io.wdd.common.beans.executor.ExecutionMessage;
import io.wdd.common.beans.rabbitmq.OctopusMessage;
import io.wdd.common.beans.rabbitmq.OctopusMessageType;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

import static io.wdd.agent.executor.config.ExecutorFunctionNacosCollector.ALL_FUNCTION_MAP;

@Component
public class OMHandlerExecutor extends AbstractOctopusMessageHandler {

    @Resource
    CommandExecutor commandExecutor;

    @Resource
    FunctionExecutor functionExecutor;

    @Resource
    ObjectMapper objectMapper;

    @Override
    public boolean handle(OctopusMessage octopusMessage) {



        if (!octopusMessage






                .getType()
                .equals(OctopusMessageType.EXECUTOR)) {
            return next.handle(octopusMessage);
        }

        boolean isScheduledScript = false;

        try {

            // 需要首先解析成 ExecutionMessage

            ExecutionMessage executionMessage = objectMapper.readValue(
                    (String) octopusMessage.getContent(),
                    new TypeReference<ExecutionMessage>() {
                    }
            );


            // add in 2023-1-17
            if (CollectionUtils.isNotEmpty(executionMessage.getMultiLineCommand())) {
                // 传递的是 页面定时任务脚本
                functionExecutor.execute(octopusMessage, executionMessage, true);
                return true;
            }

            // 只有 在预先定义的脚本缓存中查找到 才执行 功能类型
            String executionType = executionMessage.getType();
            if (ALL_FUNCTION_MAP.containsKey(executionType)) {
                // execute the exist function
                functionExecutor.execute(octopusMessage, executionMessage, false);
            } else {
                // handle command
                commandExecutor.execute(octopusMessage, executionMessage);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return true;
    }
}
