package uk.ac.ebi.biosamples.neo.service.modelconverter;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Service;

import uk.ac.ebi.biosamples.model.Attribute;
import uk.ac.ebi.biosamples.model.ExternalReference;
import uk.ac.ebi.biosamples.model.Relationship;
import uk.ac.ebi.biosamples.model.Sample;
import uk.ac.ebi.biosamples.neo.model.NeoAttribute;
import uk.ac.ebi.biosamples.neo.model.NeoExternalReference;
import uk.ac.ebi.biosamples.neo.model.NeoRelationship;
import uk.ac.ebi.biosamples.neo.model.NeoSample;

@Service
public class SampleToNeoSampleConverter
		implements Converter<Sample, NeoSample> {
	
	public SampleToNeoSampleConverter() {
		
	}

	@Override
	public NeoSample convert(Sample sample) {
		Collection<NeoAttribute> neoAttributes = new ArrayList<>();
		Collection<NeoExternalReference> neoExternalReferences = new ArrayList<>();
		
		for (Attribute attribute : sample.getCharacteristics()) {
			neoAttributes.add(NeoAttribute.build(attribute.getType(), attribute.getValue(), attribute.getIri(), attribute.getUnit()));
		}
		for (ExternalReference externalReference : sample.getExternalReferences()) {
			neoExternalReferences.add(NeoExternalReference.build(externalReference.getUrl()));
		}	
		
		NeoSample neoSample = NeoSample.build(sample.getName(), sample.getAccession(), sample.getRelease(), sample.getUpdate(),
				neoAttributes, null, neoExternalReferences);

		for (Relationship relationship : sample.getRelationships()) {

			NeoSample owner = NeoSample.create(relationship.getSource());
			NeoSample target = NeoSample.create(relationship.getTarget());
			
			if (owner.getAccession().equals(sample.getAccession())) {
				owner = neoSample;
			}
			if (target.getAccession().equals(sample.getAccession())) {
				target = neoSample;
			}
						
			neoSample.getRelationships().add(NeoRelationship.build(owner, relationship.getType(), target));
		}			
		
		return neoSample;	
	}

}

@@ -1579,19 +1579,21 @@
 le owner
- = 
+;%0A%09%09%09
 NeoSampl
@@ -1585,39 +1585,51 @@
 er;%0A%09%09%09NeoSample
-.create
+ target;%0A%09%09%09%0A%09%09%09if 
 (relationship.ge
@@ -1641,30 +1641,86 @@
 ce()
-);%0A%09%09%09NeoSample target
+.equals(sample.getAccession())) %7B%0A%09%09%09%09owner = neoSample;%0A%09%09%09%7D else %7B%0A%09%09%09%09owner
  = N
@@ -1755,22 +1755,22 @@
 .get
-Target
+Source
 ());%0A%09%09%09
 %0A%09%09%09
@@ -1765,24 +1765,25 @@
 ());%0A%09%09%09
+%7D
 %0A%09%09%09if (
 owner.ge
@@ -1778,26 +1778,30 @@
 if (
-owner.getAccession
+relationship.getTarget
 ().e
@@ -1828,37 +1828,38 @@
 ssion())) %7B%0A%09%09%09%09
-owner
+target
  = neoSample;%0A%09%09
@@ -1864,93 +1864,71 @@
 %09%09%09%7D
-%0A%09%09%09if (target.getAccession().equals(sample.getAccession())) %7B%0A%09%09%09%09target = neoSample
+ else %7B%0A%09%09%09%09target = NeoSample.create(relationship.getTarget())
 ;%0A%09%09

tweak for cleaner code