package ru.nbch.indicsearchservice.aggregator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.mutable.MutableLong;
import org.springframework.stereotype.Component;
import ru.nbch.indicsearchservice.config.settings.ApplicationSettings;
import ru.nbch.indicsearchservice.model.enums.DataType;
import ru.nbch.indicsearchservice.model.enums.SearchParameter;
import ru.nbch.indicsearchservice.util.IndicSearchCommon;

@Component
public class GutdfRuUidFileAggregator implements FileAggregator {
    private final ApplicationSettings settings;
    private final FileAggregatorCommon fileAggregatorCommon;

    public GutdfRuUidFileAggregator(ApplicationSettings settings,
                                    FileAggregatorCommon fileAggregatorCommon) {
        this.settings = settings;
        this.fileAggregatorCommon = fileAggregatorCommon;
    }

    @Override
    public Path aggregateFiles(UUID taskId, DataType dataType, SearchParameter searchParameter, String searchValue, String memberCode, Map<String, Path> tableFileMap, MutableLong rowCounter) {
        if (dataType == DataType.GUTDF || dataType == DataType.RUTDF) {
            if (searchParameter == SearchParameter.UUID || searchParameter == SearchParameter.ACCT_NUM) {
                Path aggregatedFile = settings.getStorageDirectory().toPath().resolve("AGGREGATED-" + taskId + ".csv");

                try (BufferedWriter aggregatedFileWriter = Files.newBufferedWriter(aggregatedFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
                    if (searchParameter == SearchParameter.UUID) {
                        fileAggregatorCommon.aggregateRuUidFiles(aggregatedFileWriter, tableFileMap, memberCode, null, searchValue, rowCounter);
                    } else {
                        fileAggregatorCommon.aggregateRuUidFiles(aggregatedFileWriter, tableFileMap, memberCode, searchValue, null, rowCounter);
                    }

                    aggregatedFileWriter.write("EOF");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                return aggregatedFile;
            }
        }

        return null;
    }
}
