package ru.nbch.indicsearchservice.util;

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.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.stereotype.Component;
import ru.nbch.indicsearchservice.config.settings.ApplicationSettings;

@Component
public class IndicSearchUtils {
    private final ApplicationSettings settings;

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

    public Path writeRowsToFile(UUID taskId,
                                String tableName,
                                Cursor<LinkedHashMap<String, Object>> databaseCursor) {
        return writeRowsToFile(taskId, tableName, databaseCursor, null);
    }

    public Path writeRowsToFile(UUID taskId,
                                String tableName,
                                Cursor<LinkedHashMap<String, Object>> databaseCursor,
                                Set<Integer> foundFids) {
        Path resultFile = settings.getStorageDirectory().toPath().resolve(tableName + "_" + taskId + ".csv");

        try (BufferedWriter writer = Files.newBufferedWriter(resultFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
            for (LinkedHashMap<String, Object> row : databaseCursor) {
                StringBuilder sb = new StringBuilder();
                sb.append(tableName).append("%%%");

                for (Map.Entry<String, Object> entry : row.entrySet()) {
                    String columnName = entry.getKey();
                    Object columnValue = entry.getValue();

                    sb.append(columnName.toUpperCase()).append("%%%");

                    if (columnValue != null) {
                        if (foundFids != null && columnName.equals("FID")) {
                            foundFids.add(Integer.parseInt(columnValue.toString()));
                        }

                        sb.append(columnValue).append("%%%");
                    } else {
                        sb.append("%%%");
                    }
                }

                sb.deleteCharAt(sb.length() - 1);
                writer.write(sb.toString());
                writer.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return resultFile;
    }
}
