package uk.ac.ebi.biosamples;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import uk.ac.ebi.biosamples.models.NeoRelationship;
import uk.ac.ebi.biosamples.models.NeoSample;
import uk.ac.ebi.biosamples.models.SimpleSample;
import uk.ac.ebi.biosamples.repos.NeoRelationshipRepository;
import uk.ac.ebi.biosamples.repos.NeoSampleRepository;

@Service
public class MessageHandlerNeo4J {

	@Autowired
	private NeoSampleRepository neoSampleRepository;

	@Autowired
	private NeoRelationshipRepository neoRelRepository;

	@RabbitListener(queues = Messaging.queueToBeIndexedNeo4J)
	@Transactional
	public void handle(SimpleSample sample) {
		NeoSample neoSample = neoSampleRepository.findByAccession(sample.getAccession());
		if (neoSample == null) {
			// make a new one
			neoSample = new NeoSample(sample.getAccession());
			neoSample = neoSampleRepository.save(neoSample);
		}

		for (String relType : sample.getRelationshipTypes()) {
			for (String targetAcc : sample.getRelationshipTargets(relType)) {
				// convert the target accession into a target object
				NeoSample targetSample = neoSampleRepository.findByAccession(targetAcc);
				// if it doesn't exist, create it
				if (targetSample == null) {
					targetSample = new NeoSample(targetAcc);
					targetSample = neoSampleRepository.save(targetSample);
				}
				NeoRelationship rel = NeoRelationship.create(neoSample, targetSample, relType);
				rel = neoRelRepository.save(rel);
				neoSample.getRelationships().add(rel);
			}
		}

		neoSample = neoSampleRepository.save(neoSample);
	}
}

@@ -817,24 +817,8 @@
 J)%0A%09
-@Transactional%0A%09
 publ
@@ -831,16 +831,271 @@
 d handle
+(SimpleSample sample) %7B%0A%09%09//see if this sample has any relationships at all%0A%09%09if (sample.getRelationshipTypes() == null %7C%7C sample.getRelationshipTypes().size() == 0) %7B%0A%09%09%09return;%0A%09%09%7D else %7B%0A%09%09%09persist(sample);%0A%09%09%7D%0A%09%7D%0A%0A%09@Transactional%0A%09private void persist
 (SimpleS
@@ -2020,13 +2020,16 @@
 ample);%0A
+%09%09%0A
 %09%7D%0A%7D%0A

Split transactional part out