package eu.dnetlib.data.utility.objectpackaging;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.wsaddressing.W3CEndpointReference;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import eu.dnetlib.data.utility.objectpackaging.rmi.ObjectPackagingException;

public class PackageQueue extends AbstractQueue {

	protected PackageQueue(W3CEndpointReference epr, ObjectProviderFactory objectProviderFactory) throws ObjectPackagingException {
		super(epr, objectProviderFactory);
	}

	public List<String> fetchNextListObject() throws ObjectPackagingException, DocumentException {
		return elementAsList(fetchNextElement());
	}

	public List<List<String>> obtainOldListObjects(int fromP, int toP) throws ObjectPackagingException, DocumentException {
		List<List<String>> res = new ArrayList<List<String>>();
		for (String old : obtainOldItems(fromP, toP)) {
			res.add(elementAsList(old));
		}
		return res;
	}

	private List<String> elementAsList(String elem) throws DocumentException, ObjectPackagingException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new StringReader(elem));
		Node root = doc.selectSingleNode("/objectRecord");
		if (root == null) {
			throw new ObjectPackagingException("Invalid package: missing root element");
		}

		List<String> response = new ArrayList<String>();
		for (Object o : root.selectNodes("./*")) {
			if (o instanceof Element) {
				response.add(((Element) o).asXML());
			}
		}
		return response;
	}

}
