package com.xhpc.pp.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.xhpc.pp.utils.SpringContextHolder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

import static com.xhpc.common.core.utils.GetIpAndPort.getLocalIP;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.logic.RegisterLogic.REGISTERED;

@Configuration
public class EarlierBeanConf {

    final SpringContextHolder springContextHolder;
    @Value("${server.port}")
    private String port;
    private static String PORT;
    private static String ipAndPort;

    public EarlierBeanConf(SpringContextHolder springContextHolder) {

        this.springContextHolder = springContextHolder;
    }

    public static boolean ifcanreg(String pileNo) throws NacosException {

        Map<String, Object> cachePile = REDIS.getCacheMap("pile:".concat(pileNo));
        if (!cachePile.isEmpty()) {
            String server = (String) cachePile.get("svcSrv");
            if (server == null) return true;
            String nacosServer = REDIS.getCacheObject("nacos").toString();
            NamingService namingService = NacosFactory.createNamingService(nacosServer);
            List<Instance> ppInstances = namingService.getAllInstances("xhpc-power-pile");
            String status = (String) cachePile.get("status");
            for (Instance i : ppInstances) { // todo make HBLogic work
                if (i.getIp().concat("#").concat(Integer.valueOf(i.getPort()).toString()).equals(server)) {
                    if (REGISTERED.equals(status)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Value("${server.port}")
    public void setPort(String port) {

        EarlierBeanConf.PORT = port;
    }

    public static String getLocalIPAndPort() {

        if (ipAndPort == null) {
            ipAndPort = getLocalIP().concat("#").concat(PORT);
        }
        return ipAndPort;
    }

}
