package pl.qumak;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Component;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import org.springframework.ws.support.MarshallingUtils;
import pl.qumak.xsd.datex2v3.MessageContainer;

import javax.xml.bind.JAXBElement;

@Component
public class Client extends WebServiceGatewaySupport {

  @Value("${pull.url}")
  private String pullUrl;

  @Value("${push.url}")
  private String pushUrl;

  public MessageContainer pullRequest() {
    System.out.println("Oczekiwanie na odpowiedź…");
    JAXBElement<MessageContainer> response;
    response = (JAXBElement<MessageContainer>) getWebServiceTemplate().sendAndReceive(
      pullUrl,
      new SoapActionCallback("http://datex2.eu/wsdl/snapshotPull/2020/pullData"),
      webServiceMessage -> {
          Unmarshaller unmarshaller = getUnmarshaller();
          if (unmarshaller == null) {
              throw new IllegalStateException(
                "No unmarshaller registered. Check configuration of WebServiceTemplate.");
          }
          return MarshallingUtils.unmarshal(unmarshaller, webServiceMessage);
      }
    );
    return response.getValue();
  }

  public MessageContainer pushRequest(MessageContainer d2LogicalModel) {
    System.out.println("Oczekiwanie na odpowiedź…");
    JAXBElement<MessageContainer> response;
    response = (JAXBElement<MessageContainer>) getWebServiceTemplate().marshalSendAndReceive(
      pushUrl,
      d2LogicalModel,
      new SoapActionCallback("http://datex2.eu/wsdl/simplePush/2020/putData"));
    return response.getValue();
  }
}
