package ru.yandex.webmaster3.storage.addurl;

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

import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.addurl.OwnerRequest;
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;

/**
 * @author leonidrom
 * <p>
 * У таблицы TTL в 5 дней по полю add_date
 */
@Repository
public class AddUrlOwnerRequestsYDao extends AbstractYDao {
    private static final String TABLE_NAME = "recrawl_owner_requests";

    @Autowired
    public AddUrlOwnerRequestsYDao() {
        super("/webmaster3/addurl", TABLE_NAME);
    }

    public void addBatch(List<OwnerRequest> batch) {
        batchUpdate(INSERT_VALUE_MAPPER, batch).execute();
    }

    public List<OwnerRequest> list(String owner) {
        var st = select(MAPPER).where(F.OWNER.eq(owner));
        return st.queryForList(Pair.of(F.URL_ID, OwnerRequest::getUrlId));
    }

    public void foreachRequest(Consumer<OwnerRequest> consumer) {
        streamReader(MAPPER, consumer);
    }

    private static final ValueDataMapper<OwnerRequest> INSERT_VALUE_MAPPER = ValueDataMapper.create(
            Pair.of(F.OWNER, r -> F.OWNER.get(r.getOwner())),
            Pair.of(F.URL_ID, r -> F.URL_ID.get(r.getUrlId())),
            Pair.of(F.ADD_DATE, r -> F.ADD_DATE.get(r.getAddDateTime()))
    );

    private static final DataMapper<OwnerRequest> MAPPER = DataMapper.create(
            F.OWNER, F.URL_ID, F.ADD_DATE, OwnerRequest::new
    );

    private static final class F {
        public static final Field<String> OWNER = Fields.stringField("owner");
        public static final Field<UUID> URL_ID = Fields.uuidField("url_id");
        public static final Field<DateTime> ADD_DATE = Fields.jodaDateTimeField("add_date");
    }
}
