package devops;

import cn.reghao.bnt.common.msg.constant.PackType;
import cn.reghao.bnt.web.WebApplication;
import cn.reghao.bnt.web.devops.aliyun.service.AliyunOss;
import cn.reghao.bnt.web.devops.app.db.repository.AppBuildingRepository;
import cn.reghao.bnt.web.devops.app.db.repository.AppDeployingRepository;
import cn.reghao.bnt.web.devops.app.db.repository.config.AppConfigRepository;
import cn.reghao.bnt.web.devops.app.db.repository.config.AppDeployConfigRepository;
import cn.reghao.bnt.web.devops.app.db.repository.log.BuildLogRepository;
import cn.reghao.bnt.web.devops.app.model.po.AppDeploying;
import cn.reghao.bnt.web.devops.app.model.po.AppDeployingNode;
import cn.reghao.bnt.web.devops.app.model.po.config.AppConfig;
import cn.reghao.bnt.web.devops.app.model.po.config.AppDeployConfig;
import cn.reghao.bnt.web.devops.app.model.po.log.BuildConsumed;
import cn.reghao.bnt.web.devops.app.model.po.log.BuildLog;
import cn.reghao.bnt.web.devops.build.db.repository.CompilerConfigRepository;
import cn.reghao.bnt.web.devops.build.model.po.CompilerBind;
import cn.reghao.bnt.web.devops.build.model.po.CompilerConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-08-17 15:53:04
 */
@Slf4j
@ActiveProfiles("dev")
@SpringBootTest(classes = WebApplication.class)
public class AppConfigTest {
    @Autowired
    AppBuildingRepository buildingRepository;
    @Autowired
    AppDeployingRepository deployingRepository;
    @Autowired
    AppConfigRepository configRepository;
    @Autowired
    AppDeployConfigRepository deployConfigRepository;
    @Test
    public void appConfigTest() {
        /*configRepository.findAll().forEach(appConfig -> {
            AppBuilding appBuilding = new AppBuilding(appConfig);
            buildingRepository.save(appBuilding);
        });*/

        deployConfigRepository.findAll().forEach(appDeployConfig -> {
            AppConfig appConfig = appDeployConfig.getAppConfig();
            AppDeploying appDeploying = deployingRepository.findByAppConfig(appConfig);
            if (appDeploying == null) {
                appDeploying = new AppDeploying(appDeployConfig);
                deployingRepository.save(appDeploying);
            } else {
                String machineId = appDeployConfig.getMachineHost().getMachineId();

                boolean exist = false;
                List<AppDeployingNode> deployingNodes = appDeploying.getDeployingNodes();
                for (AppDeployingNode deployingNode : deployingNodes) {
                    AppDeployConfig deployConfig = deployingNode.getDeployConfig();
                    String machineId1 = deployConfig.getMachineHost().getMachineId();
                    if (machineId.equals(machineId1)) {
                        exist = true;
                        break;
                    }
                }

                if (!exist) {
                    deployingNodes.add(new AppDeployingNode(appDeployConfig));
                    deployingRepository.save(appDeploying);
                }
            }
        });
    }

    /**
     * 构建应用依赖的 docker image
     *
     * @param
     * @return
     * @date 2025-10-13 16:19:21
     */
    @Test
    public void getDockerImageTest() {
        Set<String> dockerImages = configRepository.findAll().stream()
                .filter(appConfig -> appConfig.getPackerConfig().getType().equals(PackType.docker.getName()))
                .map(appConfig -> {
                    String dockerfile = appConfig.getDockerfile();
                    String[] lines = dockerfile.split(System.lineSeparator());
                    for (String line : lines) {
                        if (line.toLowerCase(Locale.ROOT).startsWith("from")) {
                            String[] arr = line.split(" ");
                            return arr[1].replace("\r", "");
                        }
                    }
                    return null;
                })
                .filter(Objects::nonNull).collect(Collectors.toSet());
        System.out.println();
    }

    @Autowired
    BuildLogRepository buildLogRepository;
    @Test
    public void buildLogTest() {
        List<BuildLog> buildLogs = buildLogRepository.findAll();
        buildLogs.forEach(buildLog -> {
            BuildConsumed buildConsumed = buildLog.getBuildConsumed();
            if (buildConsumed == null) {
                return;
            }

            Long l1 = buildConsumed.getPullConsumed();
            Long l2 = buildConsumed.getCompileConsumed();
            Long l3 = buildConsumed.getPackConsumed();
            Long l4 = buildConsumed.getPushConsumed();

            Long total = 0L;
            if (l1 != null) {
                total += l1;
            }

            if (l2 != null) {
                total += l2;
            }

            if (l3 != null) {
                total += l3;
            }

            if (l4 != null) {
                total += l3;
            }

            buildConsumed.setTotal(total/1000);
        });

        buildLogRepository.saveAll(buildLogs);
    }

    @Autowired
    CompilerConfigRepository compilerConfigRepository;
    @Test
    public void compilerTest() {
        CompilerConfig compilerConfig = compilerConfigRepository.findById(7).orElse(null);
        List<CompilerBind> list = compilerConfig.getCompilerBinds();
        list.add(new CompilerBind("/home/reghao/Downloads/0/node_modules", "/app/node_modules"));
        compilerConfigRepository.save(compilerConfig);
        System.out.println();
    }

    /**
     * 获取 Dockerfile 中使用的 image
     *
     * @param
     * @return
     * @date 2025-07-04 15:49:51
     */
    @Test
    public void dockerfileTest() {
        List<String> dockerfiles = configRepository.findAll().stream()
                .map(AppConfig::getDockerfile)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        List<String> list = new ArrayList<>();
        for (String dockerfile : dockerfiles) {
            for (String line : dockerfile.split("\n")) {
                if (line.startsWith("FROM")) {
                    list.add(line);
                }
            }
        }

        Set<String> set = list.stream()
                .map(line -> line.replace("\r", ""))
                .collect(Collectors.toSet());

        configRepository.findAll().forEach(appConfig -> {
            String appId = appConfig.getAppId();
            String dockerfile = appConfig.getDockerfile();
            if (dockerfile.contains("aspnet/file1")) {
                System.out.printf("appId -> %s\n", appId);
            }
        });

        System.out.println("---------------------------");
        set.forEach(System.out::println);
    }

    @Autowired
    AliyunOss aliyunOss;
    @Test
    public void aliyunTest() {
        String bucketName = "iquizoo-nztp";
        // 匹配 bucket 下的所有文件
        String prefix = "";
        aliyunOss.deleteObjects(bucketName, prefix);
    }
}
