package org.gcube.application.geoportal.client.plugins;

import org.gcube.application.geoportal.client.UseCaseDescriptors;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.application.geoportal.common.rest.UseCaseDescriptorsI;
import org.gcube.common.calls.jaxrs.GcubeService;
import org.gcube.common.calls.jaxrs.TargetFactory;
import org.gcube.common.clients.config.ProxyConfig;
import org.gcube.common.clients.delegates.ProxyDelegate;
import org.w3c.dom.Node;

import javax.ws.rs.client.WebTarget;
import javax.xml.namespace.QName;
import javax.xml.transform.dom.DOMResult;
import javax.xml.ws.EndpointReference;

public class UCDPlugin extends GeoportalAbstractPlugin<WebTarget, UseCaseDescriptorsI>{

    @Override
    public Exception convert(Exception fault, ProxyConfig<?, ?> config) {
        return super.convert(fault, config);
    }

    @Override
    public UseCaseDescriptorsI newProxy(ProxyDelegate<WebTarget> proxyDelegate) {
        return new UseCaseDescriptors(proxyDelegate);
    }

    @Override
    public WebTarget resolve(EndpointReference endpointReference, ProxyConfig<?, ?> proxyConfig) throws Exception {
        DOMResult result = new DOMResult();
        endpointReference.writeTo(result);
        Node node =result.getNode();
        Node child=node.getFirstChild();
        String addressString = child.getTextContent();
        GcubeService service = GcubeService.service().
                withName(new QName(InterfaceConstants.NAMESPACE,InterfaceConstants.Methods.UCD)).
                andPath(InterfaceConstants.Methods.UCD);
        return TargetFactory.stubFor(service).at(addressString);
    }
}
