package payment;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.servlet.Filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.atomikos.remoting.spring.rest.TransactionAwareRestContainerFilter;
import com.atomikos.remoting.support.HeaderNames;

@Configuration
@Description("This class is needed to modify the built-in Spring HTTP behaviour to support transactions")
public class WebConfiguration extends WebMvcConfigurerAdapter {

	@Override
	public void configureMessageConverters(
			List<HttpMessageConverter<?>> converters) {
		converters.add(new MappingJackson2HttpMessageConverter());
		converters.add(new HttpMessageConverter<Object>() {

			@Override
			public boolean canRead(Class<?> clazz, MediaType mediaType) {
				return true;
			}

			@Override
			public boolean canWrite(Class<?> clazz, MediaType mediaType) {
				return true;
			}

			@Override
			public List<MediaType> getSupportedMediaTypes() {
				return Collections.singletonList(MediaType
						.valueOf(HeaderNames.MimeType.APPLICATION_VND_ATOMIKOS_JSON));
			}

			@Override
			public void write(Object t, MediaType contentType,
					HttpOutputMessage outputMessage) throws IOException,
					HttpMessageNotWritableException {
				// TODO Auto-generated method stub

			}

			@Override
			public Object read(Class<? extends Object> clazz,
					HttpInputMessage inputMessage) throws IOException,
					HttpMessageNotReadableException {
				// TODO Auto-generated method stub
				return null;
			}
		});
	}
	
	@Bean
	@Description("Technical Spring wiring: filter to extract transactional context from incoming HTTP request")
	public Filter transactionAwareRestContainerFilter() {
	    return new TransactionAwareRestContainerFilter();
	}

	

}
