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

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

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

import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.componentlog.ComponentLog;
import com.iqser.red.service.persistence.service.v1.api.shared.model.analysislog.componentlog.ComponentLogEntry;
import com.iqser.red.service.persistence.service.v1.api.shared.mongo.document.ComponentLogEntryDocument;
import com.iqser.red.service.persistence.service.v1.api.shared.mongo.document.ComponentLogDocument;

@Mapper
public interface ComponentLogDocumentMapper {

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


    @Mapping(target = "componentLogEntries", source = "componentLogEntryDocuments")
    ComponentLog fromLogDocument(ComponentLogDocument componentLogDocument);


    ComponentLogEntry fromLogEntryDocument(ComponentLogEntryDocument componentLogEntryDocument);


    @Mapping(target = "id", expression = "java(getLogId(dossierId, fileId))")
    @Mapping(target = "componentLogEntryDocuments", expression = "java(toEntryDocumentList(getLogId(dossierId, fileId), componentLog.getComponentLogEntries()))")
    ComponentLogDocument toLogDocument(String dossierId, String fileId, ComponentLog componentLog);


    @Mapping(target = "id", expression = "java(getLogEntryId(componentLogId, componentLogEntry.getName()))")
    ComponentLogEntryDocument toLogEntryDocument(String componentLogId, ComponentLogEntry componentLogEntry);


    default ComponentLogEntryDocument toLogEntryDocument(String componentLogId, ComponentLogEntry componentLogEntry, ComponentLogEntryDocument existingEntry) {

        if (existingEntry != null && existingEntry.isOverridden()) {
            componentLogEntry.setValues(existingEntry.getValues());
            componentLogEntry.setOverridden(true);
        }
        return toLogEntryDocument(componentLogId, componentLogEntry);
    }


    default List<ComponentLogEntryDocument> toEntryDocumentList(String componentLogId, List<ComponentLogEntry> componentLogEntries) {

        return componentLogEntries.stream()
                .map(componentLogEntry -> toLogEntryDocument(componentLogId, componentLogEntry))
                .collect(Collectors.toList());
    }


    default String getLogId(String dossierId, String fileId) {

        return dossierId + "/" + fileId;
    }


    default String getLogEntryId(String componentLogId, String componentName) {

        return componentLogId + "/" + componentName;
    }


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

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

}
