package eu.eudat.models.data.dmp.adpter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.HashMap;
import java.util.Map;

public class PageAdapter extends XmlAdapter<Object, HashMap<String, String>> {
	private static final Logger logger = LoggerFactory.getLogger(PageAdapter.class);
	@Override
	public HashMap<String, String> unmarshal(Object v) throws Exception {
		Element data = (Element)v;
		HashMap<String, String> result = new HashMap<>();
		generateMap(data, result, "field");
		return result;
	}

	private void generateMap(Node root, Map<String, String> result, String target) {
		for (int i = 0; i < root.getChildNodes().getLength(); i++) {
			if (((Element)root).getTagName().equals(target)) {
				result.put(((Element) root).getAttribute("id"), root.getFirstChild().getFirstChild() != null ? root.getFirstChild().getFirstChild().getNodeValue() : "");
			} else {
				generateMap(root.getChildNodes().item(i), result, target);
			}
		}
	}

	@Override
	public Object marshal(HashMap<String, String> v) throws Exception {
		return null;
	}
}
