package com.iqser.red.service.persistence.management.v1.processor.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.DossierEntity;
import com.iqser.red.service.persistence.management.v1.processor.exception.NotFoundException;
import com.iqser.red.service.persistence.management.v1.processor.model.ManualChangesQueryOptions;
import com.iqser.red.service.persistence.management.v1.processor.service.manualredactions.ManualRedactionProviderService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.EntityLogEntry;
import com.iqser.red.service.persistence.service.v1.api.shared.model.annotations.ManualRedactions;
import com.iqser.red.service.persistence.service.v1.api.shared.mongo.service.EntityLogMongoService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class EntityLogMongoWrapperService {

    private final DossierService dossierService;
    private final EntityLogMongoService entityLogMongoService;
    private final ManualRedactionProviderService manualRedactionProviderService;
    private final EntityLogMergeService entityLogMergeService;


    public EntityLogEntry getEntityLogEntryById(String dossierId, String fileId, String annotationId) {

        return entityLogMongoService.findEntityLogEntryById(dossierId, fileId, annotationId)
                .orElseThrow(() -> new NotFoundException(getEntityLogNotEntryFoundErrorMessage(annotationId)));
    }


    public List<EntityLogEntry> getEntityLogEntriesByIds(String dossierId, String fileId, List<String> ids, boolean includeUnprocessed) {

        List<EntityLogEntry> entityLogEntries = entityLogMongoService.findEntityLogEntriesByIds(dossierId, fileId, ids);
        if (includeUnprocessed) {
            DossierEntity dossier = dossierService.getDossierById(dossierId);
            ManualRedactions unprocessedManualRedactions = manualRedactionProviderService.getManualRedactions(fileId, ManualChangesQueryOptions.unprocessedOnlyForIds(ids));
            entityLogEntries = entityLogMergeService.mergeEntityLogEntries(unprocessedManualRedactions, entityLogEntries, dossier, fileId);
        }
        return entityLogEntries;
    }


    private static String getEntityLogNotEntryFoundErrorMessage(String annotationId) {

        return String.format("EntityLogEntry does not exist for annotationId ID \"%s\"!", annotationId);
    }
}
