package ru.yandex.webmaster3.storage.antispam.threats.dao;

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

import com.fasterxml.jackson.core.type.TypeReference;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.util.json.JsonMapping;
import ru.yandex.webmaster3.storage.antispam.threats.data.ThreatsRecheckRequest;
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;

@Repository
public class HostThreatRecheckQueueYDao extends AbstractYDao {
    private static final String TABLE_NAME = "host_threat_recheck_queue";

    @Autowired
    public HostThreatRecheckQueueYDao() {
        super(PREFIX_CHECKLIST, TABLE_NAME);
    }

    public void insertHostForRecheck(WebmasterHostId hostId, DateTime recheckDate, Set<String> threats)  {
        execute(upsert(
                F.HOST_ID.value(hostId),
                F.RECHECK_DATE.value(recheckDate),
                F.THREATS.value(new ArrayList<>(threats))
        ));
    }

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

    public void forEach(Consumer<ThreatsRecheckRequest> consumer)  {
        queryForList(select(MAPPER), MAPPER).forEach(consumer);
    }

    private static final DataMapper<ThreatsRecheckRequest> MAPPER = DataMapper.create(
            F.HOST_ID, F.RECHECK_DATE, F.THREATS, ThreatsRecheckRequest::new
    );

    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<DateTime> RECHECK_DATE = Fields.jodaDateTimeField("recheck_date");
        static final Field<List<String>> THREATS = Fields.jsonField("threats", JsonMapping.STRING_LIST_REFERENCE);
    }
}

