package ru.nbch.indicsearchservice.loader.subtable;

import java.io.IOException;
import java.nio.file.Path;
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 org.springframework.transaction.annotation.Transactional;
import ru.nbch.indicsearchservice.model.TableMetaData;
import ru.nbch.indicsearchservice.util.IndicSearchUtils;
import ru.nbch.indicsearchservice.util.MapperHolder;

@Component
public class RuFundDateTableLoader implements RuUidSubTableLoader {
    private final MapperHolder mapperHolder;
    private final IndicSearchUtils indicSearchUtils;

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

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

    @Override
    @Transactional(readOnly = true)
    public void searchByRuUidFid(UUID taskId,
                                 Set<Integer> fids,
                                 Map<String, Path> tableFileMap,
                                 Map<String, TableMetaData> tableMetaDataMap) {
        try (Cursor<LinkedHashMap<String, Object>> cursor = mapperHolder.getIndicMapper().findAllByFidsFromRuFundDate(fids)) {
            tableFileMap.put(getTableName(), indicSearchUtils.writeRowsToFile(taskId, getTableName(), cursor, tableMetaDataMap));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
