package com.wecloud.im.server.discovery;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosWatch;
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
import com.wecloud.im.core.util.GetIpUtils;

import static com.wecloud.im.server.model.WsConstants.IP_NETTY_PUBLIC;


@Configuration
@EnableDiscoveryClient
public class NacosConfig {

    @Value("${netty.port}")
    private String nettyPort;
    @Resource
    private GetIpUtils getIpUtils;

    @Bean
    @ConditionalOnMissingBean
    public NacosDiscoveryProperties nacosProperties() {
        return new NacosDiscoveryProperties();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = {"spring.cloud.nacos.discovery.watch.enabled"}, matchIfMissing = true)
    public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties, ObjectProvider<ThreadPoolTaskScheduler> taskScheduler) {
        Map<String, String> metadataMap = nacosDiscoveryProperties.getMetadata();
        if (metadataMap == null) {
            metadataMap = new HashMap<>();
        }
//        metadataMap.put("startup.time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String value = getIpUtils.getPublicIp() + ":" + nettyPort;
        metadataMap.put(IP_NETTY_PUBLIC, value);
        // 设置心跳的周期，单位为秒，这里将心跳间隔设置为3秒：
        metadataMap.put(PreservedMetadataKeys.HEART_BEAT_INTERVAL, "3000");
        // 设置心跳超时时间，单位为秒，这里将心跳超时时间设为6秒，
        // 即服务端6秒收不到客户端心跳，会将该客户端注册的实例设为不健康：
        metadataMap.put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, "6000");
        // 设置实例删除的超时时间，单位为秒，这里将实例删除超时时间设为9秒，
        // 即服务端9秒收不到客户端心跳，会将该客户端注册的实例删除：
        metadataMap.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT, "9000");

        nacosDiscoveryProperties.setMetadata(metadataMap);
        return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties, taskScheduler);
    }


}
