package eu.eudat.logic.proxy.config.prefilling;

import eu.eudat.logic.proxy.config.entities.PrefillingConfig;
import org.w3c.dom.Element;

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

public class PrefillingConfigMapAdapter extends XmlAdapter<Object, Map<String, PrefillingConfig>> {
    @Override
    public Map<String, PrefillingConfig> unmarshal(Object v) throws Exception {
        Map<String, PrefillingConfig> configMap = new HashMap<>();
        Element element = (Element) v;
        JAXBContext jaxbContext = JAXBContext.newInstance(PrefillingConfig.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        for (int i = 0; i < element.getChildNodes().getLength(); i++) {
            if (element.getChildNodes().item(i).getAttributes() == null) {
                continue;
            }
            String id = element.getChildNodes().item(i).getAttributes().getNamedItem("id").getNodeValue();
            PrefillingConfig prefillingConfig = (PrefillingConfig) jaxbUnmarshaller.unmarshal(element.getChildNodes().item(i));
            prefillingConfig = configMap.put(id, prefillingConfig);
            System.out.println(prefillingConfig);
        }
        return configMap;
    }

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