package ru.yandex.webmaster3.storage.spam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.scheduling.annotation.Scheduled;
import ru.yandex.webmaster3.core.data.WebmasterHostId;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Set;

/**
 * @author avhaliullin
 */
public class IpSpamHostFilter implements ISpamHostFilter {
    private static final Logger log = LoggerFactory.getLogger(IpSpamHostFilter.class);

    private SpamHostIPsYDao spamHostIPsYDao;

    private volatile Set<String> badIPs = Collections.emptySet();

    @Override
    public boolean checkHost(WebmasterHostId hostId) {
        try {
            InetAddress address = Inet4Address.getByName(hostId.getPunycodeHostname());
            return address != null && address instanceof Inet4Address && badIPs.contains(address.getHostAddress());
        } catch (UnknownHostException e) {
            log.error("Failed to resolve host " + hostId);
            return false;
        }
    }

    @Scheduled(fixedDelay = 1000 * 60 * 5, initialDelay = 0)
    public void updateIPs()  {
        badIPs = spamHostIPsYDao.listIPs();
        log.info("Loaded {} spam ips", badIPs.size());
    }

    @Required
    public void setSpamHostIPsYDao(SpamHostIPsYDao spamHostIPsYDao) {
        this.spamHostIPsYDao = spamHostIPsYDao;
    }
}
