package com.sikey.wa04.business.application.converter;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.sikey.wa04.business.domain.entity.UserId;
import com.sikey.wa04.business.domain.entity.websocket.Connection;
import com.sikey.wa04.common.constants.LocaleConstant;
import com.sikey.wa04.common.exception.BusinessException;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpStatus;
import org.springframework.web.socket.WebSocketSession;

import java.time.Instant;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * 连接转换器
 *
 * @author luoyangwei
 */
@UtilityClass
public class ConnectionConverter {

    /**
     * 转换
     *
     * @param session WebSocketSession
     * @return Connection
     */
    public Connection to(WebSocketSession session) {
        Objects.requireNonNull(session.getUri());
        Map<String, String> request = HttpUtil.decodeParamMap(session.getUri().getQuery(), CharsetUtil.CHARSET_UTF_8);
        String id = request.get("id");
        String lang = request.get("lang");

        if (StrUtil.isBlank(id)) {
            throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "id is required");
        }

        Locale locale = LocaleConstant.DEFAULT_LANGUAGE;
        if (StrUtil.isNotBlank(lang)) {
            locale = Locale.forLanguageTag(lang);
        }

        String webSocketKey = session.getHandshakeHeaders().get("Sec-WebSocket-Key").getFirst();
        return new Connection()
                .setId(new UserId(id))
                .setWebsocketKey(webSocketKey)
                .setLastHeartbeat(Instant.now())
                .setLocale(locale);
    }
}
