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

import java.util.function.Consumer;

import lombok.Data;
import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
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;

/**
 * @author avhaliullin
 */
@Repository
public class HostMobileAuditQueueYDao extends AbstractYDao {
    public HostMobileAuditQueueYDao() {
        super(PREFIX_WEBMASTER3, "host_mobile_audit_queue");
    }

    public void addHost(WebmasterHostId hostId) {
        upsert(
                F.HOST_ID.value(hostId),
                F.DATE.value(DateTime.now()),
                F.RETRIES_COUNT.value(0)
        ).execute();
    }

    public void updateResendDate(WebmasterHostId hostId, int retriesCount) {
        var st = update(
                F.RESEND_DATE.set(DateTime.now()),
                F.RETRIES_COUNT.set(retriesCount)
        ).where(F.HOST_ID.eq(hostId)).getStatement();

        execute(st);
    }

    public void forEachRequest(Consumer<Record> consumer) {
        streamReader(RECORD_MAPPER, consumer);
    }

    @Nullable
    public Record getHost(WebmasterHostId hostId) {
        return select(RECORD_MAPPER)
                .where(F.HOST_ID.eq(hostId))
                .queryOne();
    }

    public void deleteHost(WebmasterHostId hostId) {
        delete().where(F.HOST_ID.eq(hostId))
                .execute();
    }

    public static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<DateTime> DATE = Fields.jodaDateTimeField("date");
        static final Field<DateTime> RESEND_DATE = Fields.jodaDateTimeField("resend_date").makeOptional();
        static final Field<Integer> RETRIES_COUNT = Fields.intField("retries_count").withDefault(0);
    }

    @Data
    public static class Record {
        private final WebmasterHostId hostId;
        private final DateTime addDate;

        @Nullable
        private final DateTime resendDate;

        private final int retriesCount;
    }

    public static final DataMapper<Record> RECORD_MAPPER = DataMapper.create(F.HOST_ID, F.DATE, F.RESEND_DATE, F.RETRIES_COUNT, Record::new);
}
