package ru.yandex.qe.dispenser.ws.base_resources.impl;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ru.yandex.qe.dispenser.domain.BotCampaignGroup;
import ru.yandex.qe.dispenser.domain.CampaignForBot;
import ru.yandex.qe.dispenser.domain.dao.bot.settings.BotCampaignGroupDao;
import ru.yandex.qe.dispenser.domain.dao.quota.request.QuotaChangeRequestDao;
import ru.yandex.qe.dispenser.domain.util.CollectionUtils;
import ru.yandex.qe.dispenser.ws.quota.request.QuotaChangeRequestManager;

import java.util.Collection;
import java.util.List;
import java.util.Set;

@Component
public class BaseResourceChangesRefreshManager {

    private final QuotaChangeRequestDao quotaChangeRequestDao;
    private final BotCampaignGroupDao botCampaignGroupDao;
    private final QuotaChangeRequestManager quotaChangeRequestManager;

    public BaseResourceChangesRefreshManager(QuotaChangeRequestDao quotaChangeRequestDao,
                                             BotCampaignGroupDao botCampaignGroupDao,
                                             QuotaChangeRequestManager quotaChangeRequestManager) {
        this.quotaChangeRequestDao = quotaChangeRequestDao;
        this.botCampaignGroupDao = botCampaignGroupDao;
        this.quotaChangeRequestManager = quotaChangeRequestManager;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void refreshBaseResourceChanges() {
        final Set<BotCampaignGroup> activeGroups = botCampaignGroupDao.getActiveGroups();
        for (BotCampaignGroup activeGroup : activeGroups) {
            final List<CampaignForBot> activeWithPredecessors = activeGroup.getActiveWithPredecessors();
            if (activeWithPredecessors.isEmpty()) {
                continue;
            }
            refreshBaseResourceChanges(CollectionUtils.ids(activeWithPredecessors));
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void refreshBaseResourceChanges(Collection<? extends Long> campaignIds) {
        List<Long> idsPage = quotaChangeRequestDao.getIdsFirstPageByCampaigns(campaignIds, 100);
        while (!idsPage.isEmpty()) {
            quotaChangeRequestManager.refreshBaseResourceChanges(idsPage);
            idsPage = quotaChangeRequestDao
                    .getIdsNextPageByCampaigns(campaignIds, idsPage.get(idsPage.size() - 1), 100);
        }
    }

}
