package de.tblsoft.solr.pipeline.filter;

import de.tblsoft.solr.pipeline.AbstractFilter;
import de.tblsoft.solr.pipeline.bean.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public abstract class AbstractSubFieldFilter extends AbstractFilter {

	private String subField;

	@Override
	public void init() {

		subField = getProperty("subField", null);
		super.init();
	}

	public List<Document> traverse(int i, String[] fieldNames, Document document) {
		List<Document> documents = document.getSubField(fieldNames[i]);
		if(documents == null) {
			return Arrays.asList(document);
		}
		List<Document> processedDocumentList = new ArrayList<>();
		for(Document d : documents) {
			if(i >= fieldNames.length - 1) {
				List<Document> processed = processDocument(d);
				processedDocumentList.addAll(processed);
			} else {
				List<Document> processed = traverse(i+1, fieldNames, d);
				processedDocumentList.addAll(processed);
			}

		}

		document.setSubField(fieldNames[i], processedDocumentList);
		return Arrays.asList(document);
	}


	@Override
	public void document(Document document) {
		List<Document> processeddDocument = null;
		if(subField != null) {
			String[] splitted = subField.split(Pattern.quote("."));
			processeddDocument = traverse(0, splitted, document);
		} else {
			processeddDocument = processDocument(document);
		}
		if(processeddDocument != null) {
			for(Document d: processeddDocument) {
				super.document(d);
			}
		}

	}

	public abstract List<Document> processDocument(Document document);

	public String getSubField() {
		return subField;
	}

	public void setSubField(String subField) {
		this.subField = subField;
	}
}

@@ -203,24 +203,46 @@
 .util.List;%0A
+import java.util.Map;%0A
 import java.
@@ -531,32 +531,68 @@
 ent document) %7B%0A
+%09%09String fieldName = fieldNames%5Bi%5D;%0A
 %09%09List%3CDocument%3E
@@ -634,20 +634,16 @@
 ieldName
-s%5Bi%5D
 );%0A%09%09if(
@@ -660,19 +660,605 @@
 == null)
+ %7B%0A%09%09%09// retrieve subfield from rawvalue field%0A%09%09%09if(document.getField(fieldName).getRawValue() != null) %7B%0A%09%09%09%09List%3CMap%3CString, Object%3E%3E rawDocs = (List%3CMap%3CString, Object%3E%3E) document.getField(fieldName).getRawValue();%0A%09%09%09%09document.deleteField(fieldName);%0A%0A%09%09%09%09for (Map%3CString, Object%3E rawDoc : rawDocs) %7B%0A%09%09%09%09%09Document subDoc = new Document();%0A%09%09%09%09%09for (Map.Entry%3CString, Object%3E entry : rawDoc.entrySet()) %7B%0A%09%09%09%09%09%09subDoc.setField(entry.getKey(), entry.getValue());%0A%09%09%09%09%09%09document.addSubField(fieldName, subDoc);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%09documents = document.getSubField(fieldName);%0A%09%09%09%7D else
  %7B%0A
+%09
 %09%09%09retur
@@ -1280,24 +1280,29 @@
 (document);%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%09List%3CD

add auto create subField from rawValue