package com.jh.radegast.rating;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jh.radegast.model.Rating;

@Service
public class RatingService {

	private static final Logger LOG = LoggerFactory.getLogger(RatingService.class);
		
	
	@Autowired
	private RatingRepository repo;

	
	@Transactional
	public void saveBulk(Collection<Rating> ratings) {
		if (ratings == null || ratings.isEmpty()) {
			return;
		}
		
		Map<String, Rating> ratingsToSave = new HashMap<>();
		for (Rating r : ratings) {
			ratingsToSave.put(r.getKey(), r);
		}

		List<Rating> existing = repo.fetchByKeys(ratingsToSave.keySet());
		if (existing != null && !existing.isEmpty()) {
			StringJoiner sj = new StringJoiner(", ");
			int duplicated = 0;
			
			for (Rating r : existing) {
				ratingsToSave.remove(r.getKey());
				sj.add(r.getKey());
				duplicated++;
			}
			
			LOG.info("Ignoring {} duplicated records: {}", duplicated, sj);
		}
		
		Collection<Rating> values = ratingsToSave.values();
		LOG.info("Storing {} ratings", values.size());
		repo.saveBulk(values);
	}
	
}
