package pl.qumak.pull;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import pl.qumak.Client;
import pl.qumak.xsd.datex2v3.MessageContainer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;

@Configuration
public class PullService extends WebServiceGatewaySupport {

    private String companyName;

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }


    public void callWebService(SpringApplicationBuilder builder)  {
        Client wsClient = builder.context().getBean(Client.class);
        MessageContainer response = wsClient.pullRequest();
        MessageContainerResponseToXml(response);
    }

    private void MessageContainerResponseToXml(MessageContainer response) {
        Writer writer = null;
        System.out.println("Odebrano komunikat od serwera KPD. Jego treść została zapisana do pliku pullResponse.xml");
        String pullResponse = marshalXmlToString(response);
        try {
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("pullResponse.xml"), "utf-8"));
            writer.write(pullResponse);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String marshalXmlToString(Object d2logicalModel) {
        String xmlString = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(MessageContainer.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(d2logicalModel, stringWriter);
            xmlString = stringWriter.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlString;
    }


}
