package ru.nbch.indicsearchservice.loader;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.ibatis.cursor.Cursor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.nbch.indicsearchservice.model.enums.DataType;
import ru.nbch.indicsearchservice.model.enums.SearchParameter;
import ru.nbch.indicsearchservice.util.IndicSearchUtils;
import ru.nbch.indicsearchservice.util.MapperHolder;

@Component
public class RuObligPartTakeTableLoader implements FirstLevelTableLoader, TableLoaderForId {
    private final MapperHolder mapperHolder;
    private final IndicSearchUtils indicSearchUtils;

    public RuObligPartTakeTableLoader(MapperHolder mapperHolder,
                                      IndicSearchUtils indicSearchUtils) {
        this.mapperHolder = mapperHolder;
        this.indicSearchUtils = indicSearchUtils;
    }

    @Override
    public String getTableName() {
        return "RU_OBLIGPARTTAKE";
    }

    @Override
    @Transactional(readOnly = true)
    public void searchBy(UUID taskId, DataType dataType, SearchParameter searchParameter, String searchValue, String memberCode, Map<String, Path> tableFileMap) {
        if (dataType == DataType.GUTDF || dataType == DataType.RUTDF) {
            if (searchParameter == SearchParameter.FID) {
                Set<Integer> fids = Set.of(Integer.parseInt(searchValue));

                try (Cursor<LinkedHashMap<String, Object>> cursor = mapperHolder.getIndicMapper().findAllByFidsFromRuObligPartTake(fids)) {
                    tableFileMap.put(getTableName(), indicSearchUtils.writeRowsToFile(taskId, getTableName(), cursor));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    @Transactional(readOnly = true)
    public void searchById(UUID taskId, DataType dataType, SearchParameter searchParameter, Set<Integer> fids, String memberCode, Map<String, Path> tableFileMap) {
        if (dataType == DataType.GUTDF || dataType == DataType.RUTDF) {
            if (searchParameter == SearchParameter.PASSPORT || searchParameter == SearchParameter.OGRN) {
                try (Cursor<LinkedHashMap<String, Object>> cursor = mapperHolder.getIndicMapper().findAllByFidsFromRuObligPartTake(fids)) {
                    tableFileMap.put(getTableName(), indicSearchUtils.writeRowsToFile(taskId, getTableName(), cursor));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
