package com.aip.gateway.api.scheduler;

import com.aip.gateway.api.config.ApplicationConfig;
import com.aip.gateway.api.model.response.GeneralResponse;
import com.aip.gateway.api.repository.AipFileRepository;
import com.aip.gateway.api.utils.Elapsed;
import jakarta.annotation.PreDestroy;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Slf4j
@AllArgsConstructor
@EnableScheduling
@Component
public class SchedulerTask {

    private final ApplicationConfig config;
    protected final AipFileRepository aipFileRepository;

    @PreDestroy
    public void onShutDown() {
        log.error("SchedulerTask.onShutDown");
    }

    //@Scheduled(cron = "${application.schedule.aip-download:40 0/30 * * * *}")
    @Scheduled(cron = "* 0/30 * * * *")
    public void scheduleAipDownload() {
        if (!this.config.isStartSchedule()) {
            return;
        }
        Elapsed elapsed = new Elapsed();
        log.info("SchedulerTask.scheduleAipDownload: start. {}", Thread.currentThread().getName());
        boolean result = runScheduleAipDownload();
        log.info("SchedulerTask.scheduleAipDownload: ..end. {} ms. result: {}, {}", elapsed.milliSeconds(), result, Thread.currentThread().getName());
    }

    private boolean runScheduleAipDownload() {
        try {
            GeneralResponse result = this.aipFileRepository.downloadAipInfo();
            return result.getErrorCode() == 0;
        }
        catch (Exception e) {
            log.error("SchedulerTask.runScheduleAipDownload: {}", e.getMessage());
            return false;
        }
    }
}
