View Javadoc
1   package io.github.magwas.inez.element;
2   
3   import java.text.MessageFormat;
4   import java.util.List;
5   import java.util.Optional;
6   
7   import org.springframework.beans.factory.annotation.Autowired;
8   import org.springframework.stereotype.Service;
9   
10  import io.github.magwas.inez.Bridi;
11  import io.github.magwas.inez.parse.IdUtil;
12  import io.github.magwas.inez.storage.FindBridiByIdService;
13  import io.github.magwas.inez.storage.SaveBridiService;
14  
15  @Service
16  public class CreateBridiElementService implements ElementConstants {
17  
18  	@Autowired
19  	SaveBridiService saveBridi;
20  
21  	@Autowired
22  	FindBridiByIdService findBridiById;
23  
24  	@Autowired
25  	BridiElementFactory bridiElementFactory;
26  
27  	public BridiElement apply(
28  			final String containerId, final String typeId, final String representation, final String... references) {
29  		String elementId = IdUtil.createID(representation);
30  		List<String> refs = List.of();
31  		if (references != null) {
32  			for (String ref : references) {
33  				if (findBridiById.apply(ref).isEmpty())
34  					throw new IllegalArgumentException("nonexisting reference:" + ref);
35  			}
36  			refs = List.of(references);
37  		}
38  		Bridi element = new Bridi(elementId, representation, refs);
39  		String isAId = IdUtil.createID(representation + "isA");
40  		Optional<Bridi> typeP = findBridiById.apply(typeId);
41  		if (typeP.isEmpty()) throw new IllegalArgumentException("unknown type:" + typeId);
42  		Bridi type = new Bridi(
43  				isAId,
44  				MessageFormat.format(IS_A_REPR, representation, typeP.get().representation()),
45  				List.of(IS_A_ID, elementId, typeId));
46  		Optional<Bridi> containerP = findBridiById.apply(containerId);
47  		if (containerP.isEmpty()) throw new IllegalArgumentException("unknown container:" + containerId);
48  		String containsId = IdUtil.createID(representation + "Contains");
49  		Bridi location = new Bridi(
50  				containsId,
51  				MessageFormat.format(CONTAINS_REPR, containerP.get().representation(), representation),
52  				List.of(CONTAINS_ID, containerId, elementId));
53  		saveBridi.apply(List.of(element, type, location));
54  		return bridiElementFactory.apply(elementId);
55  	}
56  }