package at.procon.dip.ingestion.camel;

import at.procon.dip.domain.access.DocumentAccessContext;
import at.procon.dip.domain.access.DocumentVisibility;
import at.procon.dip.domain.document.SourceType;
import at.procon.dip.domain.tenant.TenantRef;
import at.procon.dip.ingestion.service.DocumentIngestionGateway;
import at.procon.dip.ingestion.spi.OriginalContentStoragePolicy;
import at.procon.dip.ingestion.spi.SourceDescriptor;
import at.procon.dip.ingestion.config.DipIngestionProperties;
import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.OffsetDateTime;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@ConditionalOnRuntimeMode(RuntimeMode.NEW)
@RequiredArgsConstructor
@Slf4j
public class GenericFileSystemIngestionRoute extends RouteBuilder {

    private final DipIngestionProperties properties;
    private final DocumentIngestionGateway ingestionGateway;

    @Override
    public void configure() {
        if (!properties.isEnabled() || !properties.isFileSystemEnabled()) {
            log.info("Phase 4 generic filesystem ingestion route disabled");
            return;
        }

        var config = properties;
        log.info("Configuring Phase 4 generic filesystem ingestion from {}", config.getInputDirectory());

        fromF("file:%s?recursive=true&include=%s&delay=%d&maxMessagesPerPoll=%d&move=%s&moveFailed=%s",
                config.getInputDirectory(),
                config.getFilePattern(),
                config.getPollInterval(),
                config.getMaxMessagesPerPoll(),
                config.getProcessedDirectory(),
                config.getErrorDirectory())
                .routeId("dip-generic-filesystem-ingestion")
                .process(exchange -> processFile(exchange))
                .log("Imported generic document from ${header.CamelFileAbsolutePath}");
    }

    private void processFile(Exchange exchange) throws Exception {
        Path path = exchange.getIn().getBody(Path.class);
        if (path == null) {
            String absolutePath = exchange.getIn().getHeader(Exchange.FILE_PATH, String.class);
            path = Path.of(absolutePath);
        }
        byte[] payload = Files.readAllBytes(path);
        Map<String, String> attributes = new LinkedHashMap<>();
        String languageCode = properties.getDefaultLanguageCode();
        if (StringUtils.hasText(languageCode)) {
            attributes.put("languageCode", languageCode);
        }

        SourceDescriptor descriptor = new SourceDescriptor(
                buildDefaultAccessContext(),
                SourceType.FILE_SYSTEM,
                path.getFileName().toString(),
                path.toAbsolutePath().toString(),
                path.getFileName().toString(),
                Files.probeContentType(path),
                payload,
                null,
                OffsetDateTime.now(),
                OriginalContentStoragePolicy.DEFAULT,
                attributes
        );
        ingestionGateway.ingest(descriptor);
    }

    private DocumentAccessContext buildDefaultAccessContext() {
        String ownerTenantKey = properties.getDefaultOwnerTenantKey();
        DocumentVisibility visibility = properties.getDefaultVisibility();
        if (!StringUtils.hasText(ownerTenantKey)) {
            return new DocumentAccessContext(null, visibility);
        }
        return new DocumentAccessContext(new TenantRef(null, ownerTenantKey, ownerTenantKey), visibility);
    }
}
