package eu.dnetlib.is.protocol;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import eu.dnetlib.data.is.protocol.model.Protocol;
import eu.dnetlib.data.is.protocol.model.ProtocolParam;
import eu.dnetlib.data.is.protocol.repository.ProtocolParamRepository;
import eu.dnetlib.data.is.protocol.repository.ProtocolRepository;

@Service
public class ProtocolService {

	@Autowired
	private ProtocolRepository protocolRepository;

	@Autowired
	private ProtocolParamRepository protocolParamRepository;

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

	@Transactional
	public List<ProtocolDesc> listProtocols() {

		final Map<String, List<ProtocolParam>> params = protocolParamRepository.findAll()
			.stream()
			.collect(Collectors.groupingBy(ProtocolParam::getProtocol));

		return protocolRepository.findAll()
			.stream()
			.map(Protocol::getId)
			.map(id -> new ProtocolDesc(id, params.containsKey(id) ? params.get(id) : new ArrayList<>()))
			.sorted(Comparator.comparing(ProtocolDesc::getId))
			.collect(Collectors.toList());

	}

	@Transactional
	public void deleteProtocols(final String... ids) {
		for (final String id : ids) {
			protocolRepository.deleteById(id);
		}
	}

	@Transactional
	public void saveProtocol(final ProtocolDesc protocol) {
		log.info("Saving protocol: " + protocol);

		if (protocolRepository.existsById(protocol.getId())) {
			protocolParamRepository.deleteByProtocol(protocol.getId());
		} else {
			protocolRepository.save(new Protocol(protocol.getId()));
		}

		for (final ProtocolParam p : protocol.getParams()) {
			p.setProtocol(protocol.getId());
			protocolParamRepository.save(p);
		}

	}

}
