package com.charego.lingo.server;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

	@Override
	public void configureClientInboundChannel(ChannelRegistration registration) {
		// Single thread unless/until more threads are needed
		registration.taskExecutor().corePoolSize(1);
	}

	@Override
	public void configureClientOutboundChannel(ChannelRegistration registration) {
		// Single thread unless/until more threads are needed
		registration.taskExecutor().corePoolSize(1);
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker("/topic")
			.setTaskScheduler(heartbeatScheduler())
			.setHeartbeatValue(heartbeatValue());
		registry.setApplicationDestinationPrefixes("/app", "/user");
		registry.setUserDestinationPrefix("/user");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/sockjs").setAllowedOrigins("*").withSockJS();
		registry.addEndpoint("/stomp").setAllowedOrigins("*");
	}

	private TaskScheduler heartbeatScheduler() {
		// Single thread unless/until more threads are needed
		final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(1);
		taskScheduler.setThreadNamePrefix("Keep-Alive-");
		taskScheduler.initialize();
		return taskScheduler;
	}

	private long[] heartbeatValue() {
		return new long[] { 25000, 25000 };
	}

}
