package ru.yandex.webmaster3.storage.crawl.dao;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.storage.crawl.BaseCrawlInfo;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.ValueDataMapper;

/**
 * Created by kravchenko99 on 26.01.21.
 * expiration_time для этой таблицы 7 дней по полю add_date
 */
@Repository
public class BaseCrawlInfoYDao extends AbstractYDao {

    private static final String TABLE_NAME = "base_crawl_info";

    public BaseCrawlInfoYDao() {
        super(PREFIX_CRAWL, TABLE_NAME);
    }

    public void updateInfo(List<Pair<String, BaseCrawlInfo>> info, DateTime addDate) {
        if (info.isEmpty()) {
            return;
        }
        final List<Triple<String, Double, DateTime>> items = info.stream()
                .map(x -> Triple.of(x.getLeft(), x.getRight().getCrawlRPS(), addDate))
                .collect(Collectors.toList());

        batchInsert(VALUE_MAPPER, items).execute();
    }

    public BaseCrawlInfo getInfo(String hostPattern, DateTime addDate) {
        return select(MAPPER)
                .where(F.HOST_PATTERN.eq(hostPattern))
                .and(F.ADD_DATE.eq(addDate))
                .queryOne();
    }

    private static final ValueDataMapper<Triple<String, Double, DateTime>> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_PATTERN, Triple::getLeft),
            Pair.of(F.CRAWL_RPS, Triple::getMiddle),
            Pair.of(F.ADD_DATE, Triple::getRight)
    );

    private static final DataMapper<BaseCrawlInfo> MAPPER = DataMapper.create(F.CRAWL_RPS, BaseCrawlInfo::new);

    private static class F {
        static final Field<String> HOST_PATTERN = Fields.stringField("host_pattern");
        static final Field<Double> CRAWL_RPS = Fields.doubleField("crawl_rps");
        static final Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
    }
}
