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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.iqser.red.service.persistence.management.v1.processor.dataexchange.models.manualchanges.ManualChangesExportModel;
import com.iqser.red.service.persistence.service.v1.api.shared.model.FileAttribute;
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.model.analysislog.entitylog.EntityLog;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.Dossier;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileModel;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FileExchangeImportModel {

    ImportTemplateResult importTemplateResult;

    @Builder.Default
    List<Dossier> dossiers = new ArrayList<>();

    @Builder.Default
    Map<String, EntityTypeImportModel> dossierTypes = new HashMap<>();

    @Builder.Default
    Map<String, List<FileImport>> files = new HashMap<>();

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class FileImport {

        String id;
        FileModel fileModel;
        @Builder.Default
        List<FileWithType> filesToUpload = new ArrayList<>();
        EntityLog entityLog;
        ComponentLog componentLog;
        List<ComponentLogEntry> overrides;
        @Builder.Default
        ManualChangesExportModel manualChanges = new ManualChangesExportModel();
        @Builder.Default
        List<FileAttribute> fileAttributes = new ArrayList<>();

    }


    public FileImport getOrCreateFile(String dossierId, String fileId) {

        if (!files.containsKey(dossierId)) {
            FileImport file = FileImport.builder().id(fileId).build();
            List<FileImport> fileList = new LinkedList<>();
            fileList.add(file);
            files.put(dossierId, fileList);
            return file;
        }

        Optional<FileImport> optionalFile = files.get(dossierId)
                .stream()
                .filter(file -> file.getId().equals(fileId))
                .findFirst();

        if (optionalFile.isPresent()) {
            return optionalFile.get();
        }

        FileImport file = FileImport.builder().id(fileId).build();
        files.get(dossierId).add(file);
        return file;
    }

}
