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.nio.charset.StandardCharsets;
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 MimeMessageDocumentExtractor implements DocumentExtractor {

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

    @Override
    public ExtractionResult extract(ExtractionRequest extractionRequest) {
        String text = extractionRequest.textContent();
        if (!StringUtils.hasText(text) && extractionRequest.binaryContent() != null) {
            text = new String(extractionRequest.binaryContent(), StandardCharsets.UTF_8);
        }
        text = text == null ? null : text.replace("\r\n", "\n").replace('\r', '\n').trim();

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

        if (!StringUtils.hasText(text)) {
            return new ExtractionResult(Map.of(), List.of(new ExtractedStructuredPayload("mail-message", attributes)),
                    List.of("Mail message did not contain extractable text body"));
        }

        return new ExtractionResult(
                Map.of(ContentRole.NORMALIZED_TEXT, text),
                List.of(new ExtractedStructuredPayload("mail-message", attributes)),
                List.of()
        );
    }
}
