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

import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntityComponentMappingVersionEntity;
import com.iqser.red.service.persistence.management.v1.processor.entity.dossier.FileEntity;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileErrorInfo;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileModel;

public class FileModelMapper implements BiConsumer<FileEntity, FileModel> {

    @Override
    public void accept(FileEntity fileEntity, FileModel fileModel) {

        fileEntity.getFileAttributes()
                .forEach(fa -> fileModel.getFileAttributes().put(fa.getFileAttributeId().getFileAttributeConfigId(), fa.getValue()));
        fileModel.setFileErrorInfo(new FileErrorInfo(fileEntity.getErrorCause(), fileEntity.getErrorQueue(), fileEntity.getErrorService(), fileEntity.getErrorTimestamp(), fileEntity.getErrorCode()));
        fileModel.setComponentMappingVersions(getComponentMappingVersions(fileEntity));
        if (fileEntity.getLastDownload() != null) {
            fileModel.setLastDownloadDate(fileEntity.getLastDownload().getCreationDate());
        }
    }


    private static Map<String, Integer> getComponentMappingVersions(FileEntity fileEntity) {

        if (Objects.isNull(fileEntity.getComponentMappingVersions())) {
            return Collections.emptyMap();
        }
        return fileEntity.getComponentMappingVersions()
                .stream()
                .collect(Collectors.toMap(FileEntityComponentMappingVersionEntity::getName, FileEntityComponentMappingVersionEntity::getVersion));
    }

}
