package info.elexis.server.core.connector.elexis.services;

import java.util.List;

import ch.rgw.tools.TimeTool;
import info.elexis.server.core.connector.elexis.billable.tarmed.TarmedKumulationType;
import info.elexis.server.core.connector.elexis.jpa.model.annotated.TarmedGroup;
import info.elexis.server.core.connector.elexis.jpa.model.annotated.TarmedKumulation;
import info.elexis.server.core.connector.elexis.jpa.model.annotated.TarmedLeistung;

public class TarmedExclusion {

	private String slaveCode;
	private TarmedKumulationType slaveType;

	public TarmedExclusion(TarmedKumulation kumulation) {
		slaveCode = kumulation.getSlaveCode();
		slaveType = TarmedKumulationType.ofArt(kumulation.getSlaveArt());
	}

	public boolean isMatching(TarmedLeistung tarmedLeistung, TimeTool date) {
		if (slaveType == TarmedKumulationType.CHAPTER) {
			return isMatchingChapter(tarmedLeistung);
		} else if (slaveType == TarmedKumulationType.SERVICE) {
			return slaveCode.equals(tarmedLeistung.getCode());
		} else if (slaveType == TarmedKumulationType.GROUP) {
			List<String> groups = tarmedLeistung.getServiceGroups(date);
			return groups.contains(slaveCode);
		}
		return false;
	}

	private boolean isMatchingChapter(TarmedLeistung tarmedLeistung) {
		if (slaveCode.equals(tarmedLeistung.getCode())) {
			return true;
		} else {
			String parentId = tarmedLeistung.getParent();
			if (parentId != null && !parentId.equals("NIL")) {
				TarmedLeistung parent = TarmedLeistungService.load(parentId).get();
				return isMatchingChapter(parent);
			} else {
				return false;
			}
		}
	}

	public boolean isMatching(TarmedGroup tarmedGroup) {
		if (slaveType != TarmedKumulationType.GROUP) {
			return false;
		}
		return slaveCode.equals(tarmedGroup.getGroupName());
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(TarmedKumulationType.toString(slaveType)).append(" ").append(slaveCode);
		return sb.toString();
	}
}

@@ -75,16 +75,76 @@
 il.List;
+%0Aimport java.util.Optional;%0A%0Aimport org.slf4j.LoggerFactory;
 %0A%0Aimport
@@ -1493,16 +1493,25 @@
 ) %7B%0A%09%09%09%09
+Optional%3C
 TarmedLe
@@ -1516,16 +1516,17 @@
 Leistung
+%3E
  parent 
@@ -1567,16 +1567,41 @@
 tId)
-.get();%0A
+;%0A%09%09%09%09if (parent.isPresent()) %7B%0A%09
 %09%09%09%09
@@ -1631,19 +1631,26 @@
 r(parent
+.get()
 );%0A
+%09
 %09%09%09%7D els
@@ -1653,24 +1653,199 @@
  else %7B%0A%09%09%09%09
+%09LoggerFactory.getLogger(TarmedExclusion.class)%0A%09%09%09%09%09%09%09.error(%22Parent %5B%7B%7D%5D for TarmedLeistung %5B%7B%7D%5D not resolvable, returning false.%22, parentId, tarmedLeistung);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%09
 return false
@@ -1845,21 +1845,16 @@
 n false;
-%0A%09%09%09%7D
 %0A%09%09%7D%0A%09%7D%0A

Fix potentially non-resolvable tarmed parent