/*
 *  Copyright 2017 original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.springframework.cloud.reactive.socket.config;

import io.rsocket.transport.ServerTransport;
import io.rsocket.transport.netty.server.TcpServerTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.reactive.socket.DispatchSocketAcceptor;
import org.springframework.cloud.reactive.socket.DispatcherHandler;
import org.springframework.cloud.reactive.socket.ReactiveSocketServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Vinicius Carvalho
 */
@Configuration
@EnableConfigurationProperties(ReactiveSocketProperties.class)
public class ReactiveSocketsAutoConfiguration {

	@Autowired
	private ReactiveSocketProperties properties;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Bean
	@ConditionalOnMissingBean(ServerTransport.class)
	public ServerTransport transport(){
		logger.info("Creating transport : {} on [ {}:{} ]", TcpServerTransport.class.getName(), properties.getHost(), properties.getPort());
		return TcpServerTransport.create(properties.getHost(), properties.getPort());
	}


	@Bean
	public ReactiveSocketServer reactiveSocketServer(){
		return new ReactiveSocketServer(transport(), acceptor());
	}

	@Bean
	public DispatchSocketAcceptor acceptor(){
		return new DispatchSocketAcceptor(handler());
	}

	@Bean
	public DispatcherHandler handler(){
		return new DispatcherHandler();
	}

}