package cn.reghao.autodop.dmaster.spring;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import cn.reghao.autodop.common.log.LoggerConfig;
import cn.reghao.autodop.common.mqtt.DefaultMqttClient;
import cn.reghao.autodop.common.msg.MsgQueue;
import cn.reghao.autodop.dmaster.app.model.po.config.build.BuildDir;
import cn.reghao.autodop.dmaster.app.service.config.BuildDirService;
import cn.reghao.autodop.dmaster.mqttsub.MessageListener;
import cn.reghao.autodop.dmaster.machine.db.crud.NodeLogCrud;
import cn.reghao.autodop.dmaster.util.log.Appenders;
import cn.reghao.jdkutil.machine.MachineId;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

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

/**
 * @author reghao
 * @date 2019-09-26 17:22:16
 */
@Slf4j
@Component
public class DmasterLifecycle implements ApplicationRunner, DisposableBean {
    private final MessageListener messageListener;
    private final DefaultMqttClient mqttClient;
    private final BuildDirService buildDirService;

    public DmasterLifecycle(NodeLogCrud nodeLogCrud, MessageListener messageListener,
                            BuildDirService buildDirService, DefaultMqttClient mqttClient) {
        this.messageListener = messageListener;
        this.mqttClient = mqttClient;
        this.buildDirService = buildDirService;
        initLogger(nodeLogCrud);
    }

    private void initLogger(NodeLogCrud nodeLogCrud) {
        List<Appender<ILoggingEvent>> appenders = new ArrayList<>();
        appenders.add(Appenders.mongoAppender(nodeLogCrud));
        LoggerConfig.initLogger(appenders);
    }

    @Override
    public void run(ApplicationArguments args) throws MqttException {
        subTopic();
        initBuildDir();
        log.info("autodop-master 初始化完成");
    }

    @Override
    public void destroy() {
        log.info("Dmaster 停止");
    }

    private void subTopic() throws MqttException {
        String topic = MsgQueue.dmasterTopic();
        mqttClient.sub(topic, messageListener);
    }

    private void initBuildDir() {
        log.info("初始化构建目录");
        BuildDir buildDir = buildDirService.get(MachineId.id());
        if (buildDir == null) {
            buildDirService.createAndSave();
        } else {
            buildDirService.refresh(buildDir);
        }
    }
}
