package com.lanyuanxiaoyao.service.scheduler.quartz.compaction;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.service.forest.service.HudiService;
import com.lanyuanxiaoyao.service.forest.service.InfoService;
import com.lanyuanxiaoyao.service.scheduler.utils.ScheduleHelper;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * 日常普通调度
 *
 * @author ZhangJiacheng
 * @date 2023-05-11
 */
@DisallowConcurrentExecution
public class FocusUnVersionUpdateScheduleJob extends BaseScheduleJob {
    private static final Logger logger = LoggerFactory.getLogger(FocusUnVersionUpdateScheduleJob.class);

    private final DiscoveryClient discoveryClient;
    private final InfoService infoService;
    private final HudiService hudiService;
    private final ObjectMapper mapper;

    public FocusUnVersionUpdateScheduleJob(DiscoveryClient discoveryClient, InfoService infoService, HudiService hudiService, Jackson2ObjectMapperBuilder builder) {
        this.discoveryClient = discoveryClient;
        this.infoService = infoService;
        this.hudiService = hudiService;

        this.mapper = builder.build();
    }

    public static void schedule(DiscoveryClient discoveryClient, InfoService infoService, HudiService hudiService, ObjectMapper mapper, String comment) {
        logger.info("Focus un update version schedule");
        ImmutableList<String> unUpdateVersionTableIds = infoService.nonUpdatedVersionTables();
        ScheduleHelper.schedule(
                discoveryClient,
                infoService,
                hudiService,
                mapper,
                meta -> meta.getPriority() >= 10000
                        && unUpdateVersionTableIds.contains(StrUtil.format("{}-{}", meta.getJob().getId(), meta.getAlias())),
                comment,
                Maps.immutable.empty()
        );
    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        schedule(discoveryClient, infoService, hudiService, mapper, "Focus schedule for " + now);
    }
}
