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

import java.util.List;

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.http.ActionRequest;
import ru.yandex.webmaster3.core.http.RequestFilter;
import ru.yandex.webmaster3.core.http.request.RequestContext;
import ru.yandex.webmaster3.storage.http.dao.DisabledActionsPrefixesYDao;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;

/**
 * Created by leonidrom on 08/06/2017.
 */
public class ActionDisabledFilter implements RequestFilter<ActionRequest, ActionDisabledFilterResponse> {
    private static final Logger log = LoggerFactory.getLogger(ActionDisabledFilter.class);

    private DisabledActionsPrefixesYDao disabledActionsPrefixesYDao;
    private volatile String[] disabledActionsPrefixes = new String[]{};

    @Override
    public ActionDisabledFilterResponse beforeRequest(RequestContext ctx, ActionRequest actionRequest) {
        try {
            String actionName = ctx.getActionName();
            if (isActionDisabled(actionName)) {
                return new ActionDisabledFilterResponse();
            }
        } catch (Throwable t) {
            log.error("ActionDisabledFilter error", t);
        }

        return null;
    }

    @Scheduled(fixedDelay = 1000 * 60, initialDelay = 0)
    private void loadDisabledActions() {
        try {
            List<String> prefixes = disabledActionsPrefixesYDao.getAllPrefixes();
            disabledActionsPrefixes = prefixes.toArray(new String[]{});
        } catch (WebmasterYdbException e) {
            log.error("Failed to load disabled actions prefixes", e);
        }
    }

    private boolean isActionDisabled(String actionName) {
        if (actionName == null) {
            log.error("Action name is null");
            return false;
        }

        String[] prefixes = disabledActionsPrefixes;
        for (String disabledActionPrefix : prefixes) {
            if (actionName.startsWith(disabledActionPrefix)) {
                return true;
            }
        }

        return  false;
    }

    @Required
    public void setDisabledActionsPrefixesYDao(DisabledActionsPrefixesYDao disabledActionsPrefixesYDao) {
        this.disabledActionsPrefixesYDao = disabledActionsPrefixesYDao;
    }
}
