package org.sistema.spring.ws.carinsurance;

import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;

/**
 * Configs web service
 * @author Eugenia Pérez
 */
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
	/**
	 * Registers a servlet
	 * @param applicationContext
	 * @return ServletRegistrationBean
	 */
	@Bean
	public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
		MessageDispatcherServlet servlet = new MessageDispatcherServlet();
		servlet.setApplicationContext(applicationContext);
		servlet.setTransformWsdlLocations(true);
		return new ServletRegistrationBean(servlet, "/ws/*");
	}

	@Bean(name = "cars")
	public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema carsSchema) {
		DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
		wsdl11Definition.setPortTypeName("CarPort");
		wsdl11Definition.setLocationUri("/ws");
		wsdl11Definition.setTargetNamespace("http://sistema.org/spring/ws/carinsurance");
		wsdl11Definition.setSchema(carsSchema);
		return wsdl11Definition;
	}

	/**
	 * We must specify the XSD file
	 * @return XsdSchema
	 */
	@Bean
	public XsdSchema carsSchema() {
		return new SimpleXsdSchema(new ClassPathResource("carinsurances.xsd"));
	}
}
