package cn.reghao.autodop.dmaster.app.service.bd;

import cn.reghao.autodop.common.msg.Message;
import cn.reghao.autodop.common.msg.MsgQueue;
import cn.reghao.autodop.common.msg.rpc.RpcMsg;
import cn.reghao.autodop.common.msg.rpc.RpcPayload;
import cn.reghao.autodop.common.msg.rpc.clazz.AppRpcClazz;
import cn.reghao.autodop.common.msg.rpc.dto.app.DeployParam;
import cn.reghao.autodop.common.mqtt.DefaultMqttClient;
import cn.reghao.jdkutil.machine.MachineId;
import cn.reghao.jdkutil.serializer.JsonConverter;
import cn.reghao.autodop.dmaster.app.db.query.config.AppConfigQuery;
import cn.reghao.autodop.dmaster.app.model.po.config.DeployConfig;
import cn.reghao.autodop.dmaster.app.model.po.log.BuildLog;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 应用部署
 *
 * @author reghao
 * @date 2020-03-13 10:26:22
 */
@Slf4j
@Service
public class AppDeployer {
    private DefaultMqttClient mqttClient;
    private AppConfigQuery appConfigQuery;

    public AppDeployer(DefaultMqttClient mqttClient, AppConfigQuery appConfigQuery) {
        this.mqttClient = mqttClient;
        this.appConfigQuery = appConfigQuery;
    }

    public void deploy(BuildLog buildLog) throws MqttException {
        List<DeployConfig> deployConfigs = appConfigQuery.findByAppId(buildLog.getAppId()).getDeployConfigs();
        for (DeployConfig deployConfig : deployConfigs) {
            DeployParam deployParam = new DeployParam();
            deployParam.setBuildLogId(buildLog.getId());
            deployParam.setAppId(buildLog.getAppId());
            deployParam.setPackagePath(buildLog.getPackagePath());
            deployParam.setPackType(deployConfig.getPackType());
            deployParam.setStartHome(deployConfig.getStartHome());
            deployParam.setStartScript(deployConfig.getStartScript());
            String startScript = deployConfig.getStartScript();
            deployParam.setStartScript(startScript);

            RpcPayload rpcPayload = RpcPayload.rpcPayload(AppRpcClazz.class.getSimpleName(), AppRpcClazz.deploy.name(),
                    JsonConverter.objectToJson(deployParam));
            RpcMsg rpcMsg = RpcMsg.callMsg(rpcPayload);
            Message message = Message.rpcMessage(rpcMsg);

            // TODO 对于需要返回值的 pub，需要做一个记录，pub 和 sub 一一对应
            String topic = MsgQueue.dagentTopic(MachineId.id());
            mqttClient.pubWithResult(topic, 1, message);
        }
    }

    /**
     * 部署应用
     *
     * @param
     * @return
     * @date 2020-03-13 下午1:00
     */
    public void deploy(BuildLog buildLog, List<DeployConfig> deployConfigs) {
    }
}
