package ru.yandex.webmaster3.viewer.http.filter;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.RequestFilter;
import ru.yandex.webmaster3.core.http.request.RequestContext;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.spamban.SpamBanManager;
import ru.yandex.webmaster3.storage.user.SpamBanRule;
import ru.yandex.webmaster3.storage.user.dao.SpamBanRulesYDao;
import ru.yandex.wmtools.common.data.info.IPInfo;

/**
 * @author avhaliullin
 */
@Deprecated
public class SpamBannerFilter implements RequestFilter<ActionRequest, SpamBannerFilterResponse> {
    private static final Logger log = LoggerFactory.getLogger(SpamBannerFilter.class);
    @Autowired
    private SpamBanRulesYDao spamBanRulesYDao;
    private volatile List<SpamBanRule> cachedRules = new ArrayList<>();
    @Autowired
    private SpamBanManager spamBanManager;

    @Scheduled(fixedDelay = 1000 * 60 * 10, initialDelay = 0)
    private void getDirectly() {
        try {
            cachedRules = spamBanRulesYDao.getRules();
        } catch (WebmasterYdbException e) {
            log.error("Failed to load spam rules", e);
        }
    }

    @Override
    public SpamBannerFilterResponse beforeRequest(RequestContext ctx, ActionRequest actionRequest) {
        try {
            String ipString = ctx.getHttpRequest().getParameter("userIp");
            if (ipString == null) {
                return null;
            }
            IPInfo userIp = IPInfo.createFromString(ipString);
            spamBanManager.handle(userIp);
            List<SpamBanRule> rules = cachedRules;
            for (SpamBanRule rule : rules) {
                if (rule.getIpInfo().matches(userIp) && rule.getActiveStatus()) {
                    spamBanManager.handle(rule);
                    log.warn("Request banned by rule " + rule.getRuleId());
                    return new SpamBannerFilterResponse.Banned(getClass(), "Request is banned");
                }
            }
        } catch (Exception e) {
            //Ошибки в фильтре не должны обваливать запрос
            log.error("Spam filter failed", e);
        }
        return null;
    }
}
