package at.procon.eventhub.yellowfox.service;

import at.procon.eventhub.config.EventHubProperties;
import at.procon.eventhub.dto.SchedulerTriggerMode;
import at.procon.eventhub.importing.AbstractImportScheduler;
import at.procon.eventhub.yellowfox.dto.YellowFoxD8ImportRequest;
import java.util.List;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class YellowFoxD8ImportScheduler extends AbstractImportScheduler<YellowFoxD8ImportRequest> {

    private final EventHubProperties properties;
    private final YellowFoxD8ConfiguredImportPlanService configuredPlanService;
    private final YellowFoxD8ImportExecutionService executionService;

    public YellowFoxD8ImportScheduler(
            EventHubProperties properties,
            YellowFoxD8ConfiguredImportPlanService configuredPlanService,
            YellowFoxD8ImportExecutionService executionService
    ) {
        this.properties = properties;
        this.configuredPlanService = configuredPlanService;
        this.executionService = executionService;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void triggerInitialPlansOnStartup() {
        super.triggerInitialPlansOnStartup();
    }

    @Scheduled(fixedDelayString = "${eventhub.yellow-fox.scheduler-poll-interval-ms:60000}")
    public void pollConfiguredPlans() {
        super.pollConfiguredPlans();
    }

    @Override
    protected boolean schedulerEnabled() {
        return properties.getYellowFox().isSchedulerEnabled();
    }

    @Override
    protected List<EventHubProperties.ConfiguredImportPlan> configuredPlans() {
        return properties.getYellowFox().getImportPlans();
    }

    @Override
    protected SchedulerTriggerMode schedulerTriggerMode() {
        return properties.getYellowFox().getSchedulerTriggerMode();
    }

    @Override
    protected YellowFoxD8ImportRequest createInitialRequest(EventHubProperties.ConfiguredImportPlan plan) {
        return configuredPlanService.createInitialRequest(plan);
    }

    @Override
    protected YellowFoxD8ImportRequest createScheduledRequest(EventHubProperties.ConfiguredImportPlan plan) {
        return configuredPlanService.createScheduledRequest(plan);
    }

    @Override
    protected void startImport(YellowFoxD8ImportRequest request) {
        executionService.startImport(request);
    }

    @Override
    protected void startAndExecuteImport(YellowFoxD8ImportRequest request) {
        executionService.startAndExecuteImport(request);
    }

    @Override
    protected String providerName() {
        return "yellowfox-d8";
    }
}
