package com.css.simulation.resource.monitor.infra.scheduler;

import com.css.simulation.resource.monitor.infra.minio.MinioConfiguration;
import com.css.simulation.resource.monitor.infra.mysql.mapper.AlgorithmMapper;
import com.css.simulation.resource.monitor.infra.mysql.mapper.SimulationManualProjectMapper;
import com.css.simulation.resource.monitor.infra.util.MinioUtil;
import io.minio.MinioClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class MinioCleanScheduler {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfiguration minioConfiguration;
    @Resource
    private AlgorithmMapper algorithmMapper;
    @Resource
    private SimulationManualProjectMapper simulationManualProjectMapper;


    /**
     * 每天清理一次，清理30天之前被删除的数据
     */
    @Scheduled(fixedDelay = 24 * 60 * 60 * 1000)
    @SneakyThrows
    public void clean() {
        //1 清理算法文件
        {
            List<String> objects = MinioUtil.listObjects(minioClient, minioConfiguration.getBucketName(), "algorithm");

            List<String> strings = algorithmMapper.selectMinioPaths();
            for (String object : objects) {
                if (!strings.contains(object)) {
                    MinioUtil.removeObject(minioClient, minioConfiguration.getBucketName(), object);
                }
            }
        }

        //2 清理项目文件
        {
            List<String> objects = MinioUtil.listObjects(minioClient, minioConfiguration.getBucketName(), "project");
            List<String> strings = simulationManualProjectMapper.selectIds();
            for (String object : objects) {
                String[] split = object.split("/");
                if (!strings.contains(split[1])) {
                    MinioUtil.removeObject(minioClient, minioConfiguration.getBucketName(), object);
                }
            }
        }

    }
}
