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.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 GutdfRuApplicationFileAggregator implements FileAggregator {
    private final ApplicationSettings settings;

    public GutdfRuApplicationFileAggregator(ApplicationSettings settings) {
        this.settings = settings;
    }

    @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.APPLICATION_NUMBER || searchParameter == SearchParameter.OLD_APP_NUM) {
                Path aggregatedFile = settings.getStorageDirectory().toPath().resolve("AGGREGATED-" + taskId + ".csv");

                try (BufferedWriter aggregatedFileWriter = Files.newBufferedWriter(aggregatedFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
                     BufferedReader reader = Files.newBufferedReader(tableFileMap.get("RU_APPLICATION"))) {
                    String line;

                    while ((line = reader.readLine()) != null) {
                        Optional<String> foundMemberCode = IndicSearchCommon.getRowValue(line, "MEMBER_CODE");

                        if (foundMemberCode.isPresent() && !foundMemberCode.get().startsWith(memberCode)) {
                            continue;
                        }

                        if (searchParameter == SearchParameter.APPLICATION_NUMBER && searchValue != null) {
                            searchValue = searchValue.length() > 38 ? searchValue.substring(0, 38) : searchValue;

                            Optional<String> foundApplicationNumber = IndicSearchCommon.getRowValue(line, "APPLICATION_NUMBER");

                            if (foundApplicationNumber.isPresent() && !foundApplicationNumber.get().equals(searchValue)) {
                                continue;
                            }
                        }
                        if (searchParameter == SearchParameter.OLD_APP_NUM && searchValue != null) {
                            Optional<String> foundOldAppNum = IndicSearchCommon.getRowValue(line, "OLD_APP_NUM");

                            if (foundOldAppNum.isPresent() && !foundOldAppNum.get().equals(searchValue)) {
                                continue;
                            }
                        }

                        aggregatedFileWriter.write(line);
                        aggregatedFileWriter.newLine();
                        rowCounter.increment();
                    }

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

                return aggregatedFile;
            }
        }

        return null;
    }
}
