package com.bcxin.backend.domain.syncs.dtos;

import com.bcxin.runtime.domain.syncs.dtos.DataSetDto;
import lombok.Getter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
public class DbDataImportRequestDto {
    private Collection<DataSet> dataSets;
    private String filePaths;
    private Map<String, String> urlFilePathMappings;

    private String originalRequest;

    public DbDataImportRequestDto(String originalRequest,Collection<DataSet> dataSets) {

        this.originalRequest = originalRequest;
        this.dataSets = dataSets;
        this.urlFilePathMappings = new HashMap<>();

        Map<String, String> urlFilePathMappings = new HashMap<>();
        Collection<DataSetDto.FieldValue> fieldValueList = dataSets.stream()
                .flatMap(ii -> ii.getDataRecords().stream())
                .flatMap(ii -> ii.getFieldValues().stream())
                .filter(ii -> ii.isValidFile() && ii.getPathOptions() != null)
                .collect(Collectors.toList());
        fieldValueList.forEach(fieldValue -> {
            fieldValue.getPathOptions().forEach(pathOption -> {
                urlFilePathMappings.put(pathOption.getOriginalPath(), pathOption.getPath());
            });
        });

        this.filePaths = urlFilePathMappings.keySet().stream().collect(Collectors.joining(","));
        this.urlFilePathMappings = urlFilePathMappings;
    }

    public static DbDataImportRequestDto create(String originalRequest, Collection<DataSet> dataSets) {
        return new DbDataImportRequestDto(originalRequest, dataSets);
    }

    @Getter
    public static class DataSet {
        private final String id;
        private final String mapKey;
        private final Collection<DataSetDto.Row> dataRecords;
        private final Collection<String> deletedIds;

        public DataSet(String id, String mapKey,
                       Collection<DataSetDto.Row> dataRecords,
                       Collection<String> deletedIds) {
            this.id = id;
            this.mapKey = mapKey;
            this.dataRecords = dataRecords;
            this.deletedIds = deletedIds;
        }

        public static DataSet create(String id, String mapKey,
                                     Collection<DataSetDto.Row> dataRecords,
                                     Collection<String> deletedIds) {
            return new DataSet(id, mapKey, dataRecords,deletedIds);
        }
    }
}
