package com.platform.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.EnableNacos;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
@PropertySources({
        @PropertySource({
                "classpath:application.properties"
        })
})
@EnableNacos(
    globalProperties = @NacosProperties(serverAddr = "${nacos.config.server-addr}",namespace = "${nacos.config.namespace}")
)
@NacosPropertySource(dataId = "${nacos.config.data-id}", autoRefreshed = true,type = ConfigType.PROPERTIES,groupId = "${nacos.config.group}")
public class NacosConfiguration {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @NacosInjected
    private NamingService namingService;

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${nacos.discovery.register.group-name}")
    private String groupName;

    @Value("${server.port}")
    private Integer port;

    @Value("${local.ip:#{null}}")
    private String ip;

    @PostConstruct
    public void init() {
        try {
            if(ObjectUtils.isEmpty(ip)){
                InetAddress address = InetAddress.getLocalHost();
                ip = address.getHostAddress();
            }
            logger.info("service registed {}:{}",ip,port);

            namingService.registerInstance(applicationName, groupName, ip, port);
        } catch (UnknownHostException | NacosException e) {
            e.printStackTrace();
        }
    }
}