package com.lingniu.ingest.inbound.xinda.config;

import com.lingniu.ingest.core.dispatcher.Dispatcher;
import com.lingniu.ingest.identity.VehicleIdentityRegistry;
import com.lingniu.ingest.identity.VehicleIdentityResolver;
import com.lingniu.ingest.inbound.xinda.XindaPushClient;
import com.lingniu.ingest.inbound.xinda.XindaPushEventMapper;
import com.lingniu.ingest.inbound.xinda.XindaPushRealtimeHandler;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@EnableConfigurationProperties(XindaPushProperties.class)
@ConditionalOnProperty(prefix = "lingniu.ingest.xinda-push", name = "enabled", havingValue = "true")
public class XindaPushAutoConfiguration {

    @Bean(destroyMethod = "stop")
    @ConditionalOnMissingBean
    public XindaPushClient xindaPushClient(XindaPushProperties props,
                                           VehicleIdentityResolver identityResolver,
                                           Dispatcher dispatcher) {
        return new XindaPushClient(props, identityResolver, dispatcher);
    }

    @Bean
    @ConditionalOnMissingBean
    public XindaPushEventMapper xindaPushEventMapper(VehicleIdentityResolver identityResolver,
                                                     VehicleIdentityRegistry identityRegistry) {
        return new XindaPushEventMapper(identityResolver, identityRegistry);
    }

    @Bean
    @ConditionalOnMissingBean
    public XindaPushRealtimeHandler xindaPushRealtimeHandler(XindaPushEventMapper mapper) {
        return new XindaPushRealtimeHandler(mapper);
    }

    @Bean
    public ApplicationRunner xindaPushStartupRunner(XindaPushClient client) {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) {
                client.start();
            }
        };
    }
}
