package com.zcloud.personnel.positioning.websocket;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebSocket
@RequiredArgsConstructor
@ConditionalOnProperty(
        prefix = "personnel-positioning.websocket.location",
        name = "enabled",
        havingValue = "true",
        matchIfMissing = true
)
public class PersonLocationWebSocketConfiguration implements WebSocketConfigurer {
    private final PersonLocationWebSocketHandler handler;

    @Value("${application.gateway:personnelPosition}")
    private String gateway;

    @Value("${personnel-positioning.websocket.location.allowed-origins:*}")
    private String allowedOrigins;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(handler, endpointPath())
                .setAllowedOrigins(originValues());
    }

    private String endpointPath() {
        String value = gateway == null ? "" : gateway.trim();
        while (value.startsWith("/")) {
            value = value.substring(1);
        }
        while (value.endsWith("/")) {
            value = value.substring(0, value.length() - 1);
        }
        return StringUtils.hasText(value) ? "/" + value + "/ws/location" : "/ws/location";
    }

    private String[] originValues() {
        List<String> values = new ArrayList<>();
        for (String origin : StringUtils.commaDelimitedListToStringArray(allowedOrigins)) {
            if (StringUtils.hasText(origin)) {
                values.add(origin.trim());
            }
        }
        if (values.isEmpty()) {
            values.add("*");
        }
        return values.toArray(new String[0]);
    }
}
