package ru.yandex.direct.web.entity.useractionlog;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import ru.yandex.direct.core.entity.campaign.model.CampaignTypeSource;
import ru.yandex.direct.core.entity.campaign.service.CampaignService;
import ru.yandex.direct.useractionlog.reader.model.CampaignEvent;
import ru.yandex.direct.useractionlog.reader.model.LogRecord;

import static java.util.stream.Collectors.toList;

@Service
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CampaignTypeSourceCache {
    private final CampaignService campaignService;

    private Map<Long, CampaignTypeSource> typeSourceMap;

    @Autowired
    public CampaignTypeSourceCache(CampaignService campaignService) {
        this.campaignService = campaignService;
    }

    public void initialize(List<LogRecord> records) {
        List<Long> ids = records.stream()
                .map(LogRecord::getEvent)
                .filter(e -> e instanceof CampaignEvent)
                .map(CampaignEvent.class::cast)
                .map(CampaignEvent::getCampaignId)
                .collect(toList());
        typeSourceMap = campaignService.getCampaignsTypeSourceMap(ids, false);
    }

    public Map<Long, CampaignTypeSource> getTypeSourceMap() {
        return typeSourceMap;
    }
}
