package ru.yandex.qe.dispenser.ws.quota.request.owning_cost;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Manager for refresh calculated owning cost.
 *
 * @author Ruslan Kadriev <aqru@yandex-team.ru>
 */
@Component
public class QuotaChangeOwningCostRefreshManager {
    private static final Logger LOG = LoggerFactory.getLogger(QuotaChangeOwningCostRefreshManager.class);
    private static final int MAX_REPEATS = 10000;
    private final QuotaChangeOwningCostRefreshTransactionWrapper quotaChangeOwningCostRefreshTransactionWrapper;

    public QuotaChangeOwningCostRefreshManager(
            final QuotaChangeOwningCostRefreshTransactionWrapper quotaChangeOwningCostRefreshTransactionWrapper) {
        this.quotaChangeOwningCostRefreshTransactionWrapper = quotaChangeOwningCostRefreshTransactionWrapper;
    }

    /**
     * Recalculate owning cost for request from valid campaigns.
     */
    public void refresh() {
        int i = 0;
        Long fromId = null;
        while ((fromId = quotaChangeOwningCostRefreshTransactionWrapper.execute(fromId)) != null) {
            if (++i > MAX_REPEATS) {
                LOG.warn("Infinity loop detected!");
                break;
            }
        }
    }
}
