package at.procon.dip.extraction.impl;

import at.procon.dip.domain.document.ContentRole;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.extraction.spi.DocumentExtractor;
import at.procon.dip.extraction.spi.ExtractedStructuredPayload;
import at.procon.dip.extraction.spi.ExtractionRequest;
import at.procon.dip.extraction.spi.ExtractionResult;
import at.procon.dip.ingestion.util.DocumentImportSupport;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

//@Component
public class TedPackageManifestExtractor implements DocumentExtractor {

    @Override
    public boolean supports(DocumentType documentType, String mimeType) {
        return documentType == DocumentType.TED_PACKAGE;
    }

    @Override
    public ExtractionResult extract(ExtractionRequest extractionRequest) {
        String manifest = extractionRequest.textContent();
        if (!StringUtils.hasText(manifest)) {
            manifest = "TED package: " + extractionRequest.sourceDescriptor().sourceIdentifier();
        }

        Map<String, Object> attributes = new LinkedHashMap<>();
        if (extractionRequest.sourceDescriptor().attributes() != null) {
            attributes.putAll(extractionRequest.sourceDescriptor().attributes());
        }
        String title = DocumentImportSupport.firstNonBlank(extractionRequest.sourceDescriptor().attributes(), "title", "packageId");
        if (!StringUtils.hasText(title)) {
            title = extractionRequest.sourceDescriptor().fileName();
        }
        if (StringUtils.hasText(title)) {
            attributes.put("title", title);
        }

        return new ExtractionResult(
                Map.of(ContentRole.NORMALIZED_TEXT, manifest),
                List.of(new ExtractedStructuredPayload("ted-package-manifest", attributes)),
                List.of()
        );
    }
}
