package com.lanyuanxiaoyao.service.command.commands;

import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import com.lanyuanxiaoyao.service.configuration.ExecutorProvider;
import com.lanyuanxiaoyao.service.forest.service.InfoService;
import com.lanyuanxiaoyao.service.forest.service.PulsarService;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.MutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

/**
 * @author ZhangJiacheng
 * @date 2024-01-30
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@ShellComponent("检查相关操作")
public class CheckCommand {
    private static final Logger logger = LoggerFactory.getLogger(CheckCommand.class);

    private final InfoService infoService;
    private final PulsarService pulsarService;

    public CheckCommand(InfoService infoService, PulsarService pulsarService) {
        this.infoService = infoService;
        this.pulsarService = pulsarService;
    }

    @ShellMethod("检查表topic是否对应")
    public void checkPulsarTopicExists() {
        MutableList<String> results = Lists.mutable.<String>empty().asSynchronized();
        infoService.tableMetaList()
                .asParallel(ExecutorProvider.EXECUTORS, 10)
                .forEach(meta -> {
                    logger.info("{} pulsar check...", meta.getAlias());
                    if (StrUtil.isBlank(meta.getPulsarAddress())) {
                        results.add(StrUtil.format("{} pulsar url is blank", meta.getAlias()));
                    }
                    if (StrUtil.isBlank(meta.getTopic())) {
                        results.add(StrUtil.format("{} pulsar topic is blank", meta.getAlias()));
                    }
                    if (!pulsarService.existsTopic(meta.getPulsarAddress(), meta.getTopic())) {
                        results.add(StrUtil.format("{} pulsar url {} not contain topic {}", meta.getAlias(), meta.getPulsarAddress(), meta.getTopic()));
                    }
                });
        results.toSortedList().forEach(logger::info);
    }

    @ShellMethod("杂项工具")
    public String getAllFieldType() {
        return infoService.tableMetaList()
                .flatCollect(TableMeta::getFields)
                .collect(TableMeta.FieldMeta::getType)
                .distinct()
                .toSortedList()
                .makeString("\n");
    }
}
