package ru.nbch.indicsearchservice.aggregator;

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.Map;
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;

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

    public TutdfAccountFileAggregator(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.TUTDF) {
            if (searchParameter == SearchParameter.UUID || searchParameter == SearchParameter.ACCT_NUM || searchParameter == SearchParameter.SERIAL_NUM_ACCT) {
                Path aggregatedFile = settings.getStorageDirectory().toPath().resolve("AGGREGATED-" + taskId + ".csv");

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

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

                return aggregatedFile;
            }
        }

        return null;
    }
}
