package com.priusis.config;

import com.priusis.client.service.DefaultTenantManagerService;
import com.priusis.client.service.PersistentFileService;
import com.priusis.client.service.PersistentFileServiceImpl;
import com.priusis.client.service.TenantManagerService;
import com.priusis.client.service.conf.PcCoreConfiguration;
import com.priusis.client.service.conf.PcPersistenceConfiguration;
import com.priusis.client.service.core.MqttService;
import com.priusis.client.service.core.MqttServiceImpl;
import io.netty.channel.nio.NioEventLoopGroup;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.util.function.Consumer;

@Configuration
public class PiClientConfiguration {

    public static final int NIO_EVENT_LOOP_GROUP_THREADS = 100;

    @Bean
    public TenantManagerService getTenantManagerService() {
        return new DefaultTenantManagerService() {
            @Override
            public MqttService getGatewayService(PcCoreConfiguration configuration, Consumer<String> extensionsConfigListener) {
                return getGatewayServiceBean(configuration, extensionsConfigListener);
            }
        };
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public PersistentFileService getPersistentFileServiceBean(PcPersistenceConfiguration pcPersistenceConfiguration) {
        PersistentFileServiceImpl persistentFileService = new PersistentFileServiceImpl();
        persistentFileService.setPersistence(pcPersistenceConfiguration);
        return persistentFileService;
    }


    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MqttService getGatewayServiceBean(PcCoreConfiguration configuration, Consumer<String> extensionsConfigListener) {
        MqttServiceImpl gatewayService = new MqttServiceImpl(configuration, extensionsConfigListener);
        gatewayService.setPersistentFileService(getPersistentFileServiceBean(configuration.getPersistence()));
        return gatewayService;
    }

    @Bean
    public NioEventLoopGroup getNioEventLoopGroupBean() {
        return new NioEventLoopGroup(NIO_EVENT_LOOP_GROUP_THREADS);
    }
}
