package com.lanyuanxiaoyao.service.check.actions;

import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.check.configuration.PulsarConfigurationProperties;
import com.lanyuanxiaoyao.service.configuration.entity.pulsar.PulsarInfo;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.PulsarClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

/**
 * 主机相关检查
 *
 * @author lanyuanxiaoyao
 * @date 2024-02-22
 */
@Component
@ConditionalOnBean(PulsarConfigurationProperties.class)
public class PulsarChecker extends Checker {
    private static final Logger logger = LoggerFactory.getLogger(PulsarChecker.class);

    private String adminUrl(PulsarInfo info) {
        return StrUtil.format("http://{}/admin/v2", info.getAdmin());
    }

    @Override
    public void check() throws Exception {
        for (PulsarInfo pulsarInfo : PulsarInfo.DEFAULT_INFOS) {
            logger.info("Check pulsar {}", pulsarInfo.getName());
            if (StrUtil.isNotBlank(pulsarInfo.getAdmin())) {
                logger.info("Check pulsar admin {}", pulsarInfo.getAdmin());
                if (ping(pulsarInfo.getAdmin())) {
                    // noinspection EmptyTryBlock
                    try (PulsarAdmin ignored = PulsarAdmin.builder().serviceHttpUrl(adminUrl(pulsarInfo)).build()) {
                    } catch (Exception exception) {
                        logger.warn("Pulsar admin login failure", exception);
                    }
                } else {
                    logger.warn("{} ping failure", pulsarInfo.getAdmin());
                }
            } else {
                logger.warn("Pulsar {} admin is empty", pulsarInfo.getName());
            }
            logger.info("Check pulsar nodes");
            for (String broker : pulsarInfo.getBrokers()) {
                if (!ping(broker)) {
                    logger.warn("{} ping failure", broker);
                }
            }
            String brokerUrl = "pulsar://" + pulsarInfo.getBrokers().makeString(",");
            try (PulsarClient client = PulsarClient.builder()
                    .serviceUrl(brokerUrl)
                    .build()) {
                if (client.isClosed()) {
                    logger.warn("Pulsar client failure connect {}", brokerUrl);
                }
            }
        }
    }

    @Override
    public String description() {
        return "Check Pulsar";
    }
}
