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

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

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;

import java.util.List;
import java.util.function.Consumer;

@Repository
public class UserLastVisitYDao extends AbstractYDao {
    public UserLastVisitYDao() {
        super(PREFIX_USER, "user_last_visit");
    }

    public void addVisit(long userId, Instant lastVisit) {
        upsert(
                F.USER_ID.value(userId),
                F.LAST_VISIT.value(lastVisit)
        ).execute();
    }

    public Instant getVisit(long userId) {
        return select(F.LAST_VISIT)
                .where(F.USER_ID.eq(userId))
                .queryOne();
    }

    public void forEach(Consumer<Pair<Long, Instant>> consumer) {
        streamReader(MAPPER, consumer);
    }

    public void batchInsert(List<Pair<Long, Instant>> items) {
        batchInsert(VALUE_MAPPER, items).execute();
    }

    public void deleteForUser(long userId) {
        delete().where(F.USER_ID.eq(userId)).execute();
    }

    private static class F {
        static final Field<Long> USER_ID = Fields.longField("user_id");
        static final Field<Instant> LAST_VISIT = Fields.jodaInstantField("last_visit");
    }

    private static final DataMapper<Pair<Long, Instant>> MAPPER = DataMapper.create(F.USER_ID, F.LAST_VISIT, Pair::of);
    private static final ValueDataMapper<Pair<Long, Instant>> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.USER_ID, Pair::getKey),
            Pair.of(F.LAST_VISIT, Pair::getValue)
    );
}
