package eu.dnetlib.openaire.community;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import eu.dnetlib.openaire.exporter.exceptions.CommunityException;
import eu.dnetlib.openaire.exporter.exceptions.CommunityNotFoundException;
import eu.dnetlib.openaire.exporter.model.community.CommunitySummary;
import eu.dnetlib.openaire.exporter.model.community.CommunityZenodoCommunity;

import java.util.*;

@Component
public class CommunityClientImpl implements CommunityClient {

    private static final Log log = LogFactory.getLog(CommunityClient.class);

    @Autowired
    private CommunityCommon communityCommon;

    @Override
    @Cacheable("community-cache")
    public Map<String, Set<String>> getInverseZenodoCommunityMap () throws CommunityException, CommunityNotFoundException {
        log.info("Creating the data structure. Not using cache");
        final Map<String, Set<String>> inverseListMap = new HashMap<>();

        final List<CommunitySummary> communityList = communityCommon.listCommunities();

        for(CommunitySummary cs :communityList){
            final String communityId =  cs.getId();
            List<CommunityZenodoCommunity> czc = communityCommon.getCommunityZenodoCommunities(communityId);
            for(CommunityZenodoCommunity zc:czc){
                final String zenodoId = zc.getZenodoid();
                if(!inverseListMap.containsKey(zenodoId)) {
                    inverseListMap.put(zc.getZenodoid(),new HashSet<>());
                }
                inverseListMap.get(zc.getZenodoid()).add(communityId);
            }
            final String zenodoMainCommunity = communityCommon.getCommunity(communityId).getZenodoCommunity();
            if(!inverseListMap.containsKey(zenodoMainCommunity)) {
                inverseListMap.put(zenodoMainCommunity,new HashSet<>());
            }

            inverseListMap.get(zenodoMainCommunity).add(communityId);
        }
        return inverseListMap;
    }



    @Override
    @CacheEvict(cacheNames = { "community-cache", "context-cache-community"}, allEntries = true)
    @Scheduled(fixedDelayString = "${openaire.exporter.cache.ttl}")
    public void dropCache(){
        log.debug("dropped community cache");
    }

}
