package ru.yandex.wmconsole.periodic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.scheduler.ExecutionContext;
import ru.yandex.wmconsole.data.UserBlockReason;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.util.scheduler.timetable.AbstractTaskExecutor;

/**
 * @author baton
 */
public class BanOveractiveUsersTask extends AbstractTaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(BanOveractiveUsersTask.class);

    private Integer tooSmallNotCount;
    private Integer banBorder;

    private static final String INSERT_OVERACTIVE_USERS_QUERY =
            "INSERT IGNORE INTO tbl_blocked_users(user_id, block_reason)" +
                " SELECT DISTINCT urc.user_id, ? as block_reason" +
                " FROM tbl_user_requests_count urc" +
                " LEFT JOIN tbl_blocked_users bu ON urc.user_id = bu.user_id" +
                " LEFT JOIN tbl_support_users su ON urc.user_id = su.user_id" +
                " WHERE urc.request_date >= NOW() - INTERVAL 2 DAY" +
                " AND bu.user_id IS NULL" +
                " AND su.user_id IS NULL" +
                " AND urc.count >= ?" +
                " GROUP BY urc.user_id, urc.request_date" +
                " HAVING sum(urc.count) >= ?";

    @Override
    public String runWithRELogging(ExecutionContext context) {
        log.debug("BanOveractiveUsers task fired");
        logUserDbConnections();
        String msg = null;
        if (banBorder <= 0) {
            msg = "BanOveractiveUsers: Ban border is set to 0 or less => Ban is switched off.";
            log.debug(msg);
            return msg;
        }

        try {
            int updated = getJdbcTemplate(WMCPartition.nullPartition()).update(INSERT_OVERACTIVE_USERS_QUERY,
                    UserBlockReason.AUTOMATED_REQUESTS.getValue(), tooSmallNotCount, banBorder);

            msg = "BanOveractiveUsers task OK. Banned " + updated + " users.";
            log.debug(msg);
        } catch (InternalException e) {
            msg = "BanOveractiveUsers task failed";
            log.error(msg, e);
        }
        logUserDbConnections();
        return msg;
    }

    @Required
    public void setBanBorder(int banBorder) {
        this.banBorder = banBorder;
    }

    @Required
    public void setNotCount(int notCount) {
        this.tooSmallNotCount = notCount;
    }
}
