package ru.yandex.webmaster3.storage.importanturls;

import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

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

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.importanturls.data.ImportantUrlRequest;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
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;

@Repository
public class HostsWithImportantUrlsYDao extends AbstractYDao {
    protected HostsWithImportantUrlsYDao() {
        super(PREFIX_IMPORTANT_URLS, "hosts_with_important_urls");
    }

    public void add(Collection<ImportantUrlRequest> importantUrls) {
        DateTime now = DateTime.now();
        List<Pair<WebmasterHostId, DateTime>> items = importantUrls.stream()
                .map(ImportantUrlRequest::getHostId)
                .distinct()
                .map(x -> Pair.of(x, now))
                .collect(Collectors.toList());

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

    public void iterateAllHosts(Consumer<WebmasterHostId> consumer) {
        streamReader(F.HOST_ID, consumer);
    }

    ValueDataMapper<Pair<WebmasterHostId, DateTime>> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_ID, Pair::getKey),
            Pair.of(F.ADD_DATE, Pair::getValue)
    );

    static final class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
    }
}
