package com.usky.cdi.service.sip.util;

import com.usky.cdi.service.sip.config.SipServerProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.net.DatagramSocket;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ConditionalOnProperty(prefix = "sip.server", name = "enabled", havingValue = "true")
public class PortAllocator {

    private final int minPort;
    private final int maxPort;
    private final AtomicInteger cursor;

    public PortAllocator(SipServerProperties properties) {
        this.minPort = properties.getRtpPortMin();
        this.maxPort = properties.getRtpPortMax();
        this.cursor = new AtomicInteger(minPort);
    }

    public synchronized int allocate() {
        int range = maxPort - minPort + 1;
        for (int i = 0; i < range; i++) {
            int port = cursor.getAndIncrement();
            if (port > maxPort) {
                cursor.set(minPort);
                port = minPort;
            }
            if (port % 2 != 0) {
                port++;
            }
            if (isPortAvailable(port)) {
                return port;
            }
        }
        throw new IllegalStateException("无可用 RTP 端口: " + minPort + "-" + maxPort);
    }

    private boolean isPortAvailable(int port) {
        try (DatagramSocket socket = new DatagramSocket(port)) {
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
