package com.iqser.red.service.persistence.service.v1.api.shared.mongo.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.util.List;
import java.util.stream.Collectors;

import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.EntityLog;
import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.entitylog.EntityLogEntry;
import com.iqser.red.service.persistence.service.v1.api.shared.mongo.document.EntityLogDocument;
import com.iqser.red.service.persistence.service.v1.api.shared.mongo.document.EntityLogEntryDocument;

@Mapper
public interface EntityLogDocumentMapper {

    EntityLogDocumentMapper INSTANCE = Mappers.getMapper(EntityLogDocumentMapper.class);


    @Mapping(target = "entityLogEntry", source = "entityLogEntryDocuments")
    EntityLog fromLogDocument(EntityLogDocument entityLogDocument);

    @Mapping(target = "id", source = "entityLogEntryDocument.entryId")
    EntityLogEntry fromLogEntryDocument(EntityLogEntryDocument entityLogEntryDocument);

    List<EntityLogEntryDocument> toLogEntryDocuments(List<EntityLogEntry> entityLogEntries);



    @Mapping(target = "id", expression = "java(getLogId(dossierId, fileId))")
    @Mapping(target = "entityLogEntryDocuments", expression ="java(toEntryDocumentList(getLogId(dossierId, fileId), entityLog.getEntityLogEntry()))")
    EntityLogDocument toLogDocument(String dossierId, String fileId, EntityLog entityLog);


    @Mapping(target = "id", expression = "java(getLogEntryId(entityLogId, entityLogEntry.getId()))")
    @Mapping(target = "entryId", source = "entityLogEntry.id")
    EntityLogEntryDocument toLogEntryDocument(String entityLogId, EntityLogEntry entityLogEntry);


    default List<EntityLogEntryDocument> toEntryDocumentList(String entityLogId, List<EntityLogEntry> entityLogEntries) {

        return entityLogEntries.stream()
                .map(entityLogEntry -> toLogEntryDocument(entityLogId, entityLogEntry))
                .collect(Collectors.toList());
    }


    default String getLogId(String dossierId, String fileId) {

        return dossierId + "/" + fileId;
    }


    default String getLogEntryId(String entityLogId, String entryId) {

        return entityLogId + "/" + entryId;
    }

    default String getLogEntryId(String dossierId, String fileId, String entryId) {

        return getLogId(dossierId, fileId) + "/" + entryId;
    }

}