package ru.yandex.qe.dispenser.domain.dao.bot.provider.group.report;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.qe.dispenser.domain.ProviderGroup;
import ru.yandex.qe.dispenser.domain.ProviderGroupReport;
import ru.yandex.qe.dispenser.domain.dao.bot.provider.group.ProviderGroupDaoImpl;

public class ProviderGroupReportDaoImpl implements ProviderGroupReportDao {
    @Autowired
    private ProviderGroupDaoImpl providerGroupDao;

    @NotNull
    protected final Map<Long, ProviderGroupReport.Report> id2obj = new ConcurrentHashMap<>();

    @Override
    public void upsertProviderGroupReport(final long providerGroupId, final ProviderGroupReport.Report report) {
        id2obj.put(providerGroupId, report);
    }

    @Override
    public List<ProviderGroupReport> getByCampaignId(final long campaignId) {
        final List<ProviderGroup> providerGroups = providerGroupDao.getProviderGroupsByCampaignId(campaignId);
        final List<ProviderGroupReport> result = new ArrayList<>(providerGroups.size());
        for (final ProviderGroup providerGroup : providerGroups) {
            final long providerGroupId = providerGroup.getId();
            if (id2obj.containsKey(providerGroupId)) {
                result.add(new ProviderGroupReport(
                        providerGroupId,
                        providerGroup.getName(),
                        providerGroup.getDescription(),
                        providerGroup.getPriority(),
                        id2obj.get(providerGroupId)
                ));
            }
        }
        return result;
    }

    @Override
    public boolean clear() {
        final boolean isEmpty = !id2obj.isEmpty();
        id2obj.clear();
        return isEmpty;
    }
}
