package be.fgov.ehealth.technicalconnector.tests.server.callback;

import be.ehealth.technicalconnector.utils.impl.JaxbContextFactory;
import be.fgov.ehealth.technicalconnector.tests.server.EchoResponse;
import org.mockserver.model.*;

import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class EchoExpectationCallback extends AbstractExpectationCallback {


    @Override
    public HttpResponse handle(HttpRequest httpRequest) {
        try {

            EchoResponse response = new EchoResponse();
            response.setInbound(new EchoResponse.Inbound());
            for (Header header : httpRequest.getHeaders()) {
                for (NottableString value : header.getValues()) {
                    EchoResponse.Inbound.Header inheader = new EchoResponse.Inbound.Header();
                    inheader.setId(header.getName().getValue());
                    inheader.setValue(value.getValue());
                    response.getInbound().getHeader().add(inheader);
                }
            }
            EchoResponse.Inbound.File bodyFile = new EchoResponse.Inbound.File();
            bodyFile.setId("body");
            bodyFile.setValue(new String(httpRequest.getBodyAsRawBytes()));
            response.getInbound().getFile().add(bodyFile);
            String body = toString(response);
            return wrapSOAPEnvelope(body, HttpStatusCode.OK_200);
        } catch (Exception e) {
            e.printStackTrace();
            return internalError("Unable to echo message", e);
        }
    }

    private String toString(EchoResponse response) throws Exception {
        Marshaller marshaller = JaxbContextFactory.getJaxbContextForClass(EchoResponse.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        StringWriter sw = new StringWriter();
        marshaller.marshal(response, sw);
        return sw.toString();
    }


}
