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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.wdd.agent.agent.AgentOperationInfoService;
import io.wdd.agent.agent.AgentRebootUpdateService;
import io.wdd.common.beans.agent.AgentOperationMessage;
import io.wdd.common.beans.agent.AgentOperationType;
import io.wdd.common.beans.rabbitmq.OctopusMessage;
import io.wdd.common.beans.rabbitmq.OctopusMessageType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class OMHandlerAgent extends AbstractOctopusMessageHandler {


    @Resource
    AgentRebootUpdateService agentRebootUpdateService;

    @Resource
    AgentOperationInfoService agentOperationInfoService;

    @Resource
    ObjectMapper objectMapper;


    @Override
    public boolean handle(OctopusMessage octopusMessage) {
        if (!octopusMessage
                .getType()
                .equals(OctopusMessageType.AGENT)) {
            return next.handle(octopusMessage);
        }

        AgentOperationMessage operationMessage;
        try {
            operationMessage = objectMapper.readValue(
                    (String) octopusMessage.getContent(),
                    new TypeReference<AgentOperationMessage>() {
                    }
            );
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


        AgentOperationType opType = operationMessage.getOpType();
        if (opType.equals(AgentOperationType.REBOOT)) {
            // reboot
            agentRebootUpdateService.exAgentReboot(operationMessage);
        } else if (opType.equals(AgentOperationType.UPDATE)) {
            // update
            agentRebootUpdateService.exAgentUpdate(operationMessage);
        } else if (opType.equals(AgentOperationType.VERSION)) {

            // 收集Agent的版本信息
            agentOperationInfoService.AgentOpVersion(octopusMessage);

        } else if (opType.equals(AgentOperationType.INFO)) {

            // 收集Agent的核心Info信息
            agentOperationInfoService.AgentOpInfo(octopusMessage);

        } else if (opType.equals(AgentOperationType.SHUTDOWN)) {

            // 关闭Agent的接口
            agentRebootUpdateService.exAgentShutdown(octopusMessage, operationMessage);
        } else {
            // operation unknown
            log.error("Command Agent Operation Unknown! ");
        }

        return true;
    }
}
