package cn.reghao.autodop.dmaster.mqttsub.rpcresult;

import cn.reghao.autodop.common.msg.rpc.RpcResult;
import cn.reghao.autodop.common.msg.rpc.clazz.AppRpcClazz;
import cn.reghao.autodop.common.msg.rpc.dto.app.AppStatus;
import cn.reghao.autodop.common.msg.rpc.dto.app.DeployResult;
import cn.reghao.autodop.common.mqtt.DefaultMqttClient;
import cn.reghao.jdkutil.result.ResultStatus;
import cn.reghao.jdkutil.serializer.JsonConverter;
import cn.reghao.autodop.dmaster.app.service.rpc.AppRpcClazzResultHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 分发 AppRpcClazz 相关的消息
 *
 * @author reghao
 * @date 2020-12-30 10:26:47
 */
@Slf4j
@Component
public class AppRpcClazzResult {
    private final AppRpcClazzResultHandler appRpcClazzResultService;
    private final DefaultMqttClient mqttClient;

    public AppRpcClazzResult(AppRpcClazzResultHandler appRpcClazzResultService, DefaultMqttClient mqttClient) {
        this.appRpcClazzResultService = appRpcClazzResultService;
        this.mqttClient = mqttClient;
    }

    public void process(String msgId, String method, RpcResult rpcResult) {
        mqttClient.removeRecord(msgId);
        int code = rpcResult.getCode();
        if (code != ResultStatus.SUCCESS.getCode()) {
            String msg = rpcResult.getMsg();
            log.error("error msg -> {}", msg);
            return;
        }

        switch (AppRpcClazz.valueOf(method)) {
            case deploy:
                processDeployResult(rpcResult.getJsonData());
                break;
            case start:
            case stop:
            case restart:
            case status:
                processStatusResult(rpcResult.getJsonData());
                break;
            case log:
                break;
            default:
                ;
        }
    }

    private void processDeployResult(String payload) {
        DeployResult deployResult = JsonConverter.jsonToObject(payload, DeployResult.class);
        appRpcClazzResultService.deployResult(deployResult);
    }

    private void processStatusResult(String payload) {
        AppStatus appStatus = JsonConverter.jsonToObject(payload, AppStatus.class);
        if (appStatus != null) {
            appRpcClazzResultService.statusResult(appStatus);
        }
    }
}
