package at.procon.eventhub.tachograph.service;

import at.procon.eventhub.config.EventHubProperties;
import at.procon.eventhub.dto.SchedulerTriggerMode;
import at.procon.eventhub.importing.AbstractImportScheduler;
import at.procon.eventhub.tachograph.dto.TachographImportRequest;
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 TachographImportScheduler extends AbstractImportScheduler<TachographImportRequest> {

    private final EventHubProperties properties;
    private final TachographConfiguredImportPlanService configuredPlanService;
    private final TachographImportExecutionService executionService;

    public TachographImportScheduler(
            EventHubProperties properties,
            TachographConfiguredImportPlanService configuredPlanService,
            TachographImportExecutionService executionService
    ) {
        this.properties = properties;
        this.configuredPlanService = configuredPlanService;
        this.executionService = executionService;
    }

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

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

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

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

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

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

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

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

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

    @Override
    protected String providerName() {
        return "tachograph";
    }
}
