package com.huashe.park.infrastructure.socket.client;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Map;

import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huashe.park.common.consts.BDConst;
import com.huashe.park.domain.dto.UWBAuth;
import com.huashe.park.infrastructure.cfg.forest.UWBForestCfg;

import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;

public class UWBSocketClient extends org.java_websocket.client.WebSocketClient {

    private static final Logger log = LoggerFactory.getLogger(UWBSocketClient.class);

    @Autowired
    private MqttClientTemplate client;

    @Autowired
    private UWBForestCfg uwbForestCfg;

    private UWBAuth authToken;

    public UWBAuth getAuthToken() {
        return authToken;
    }

    public void setAuthToken(UWBAuth authToken) {
        this.authToken = authToken;
    }

    public UWBSocketClient(URI serverUri) {
        super(serverUri);
    }

    public UWBSocketClient(URI serverUri, Draft protocolDraft) {
        super(serverUri, protocolDraft);
    }

    public UWBSocketClient(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) {
        super(serverUri, protocolDraft, httpHeaders, connectTimeout);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.debug("[websocket] 连接成功,{}", JSON.toJSONString(this.authToken));
        send(JSON.toJSONString(this.authToken));
    }

    @Override
    public void onMessage(String message) {
        log.debug("[websocket] 收到消息={}", message);
        JSONObject data = JSON.parseObject(message);
        if (!"handshake".equals(data.getString("message"))) {
            client.publish(String.format(BDConst.MQTT_TOPIC.UWB_VIDEO_TRACE_POINT, uwbForestCfg.getTestTag()),
                JSON.toJSONBytes(data));
            return;
        }
        this.authToken.setTagId(uwbForestCfg.getTestTag());
        log.debug("[websocket] 推送={}", JSON.toJSONString(this.authToken));
        // tagId要去掉前缀0
        send(JSON.toJSONString(this.authToken));
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        log.debug("[websocket] 收到消息={}", JSON.parseObject(bytes.array()));
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("[websocket] 退出连接");
    }

    @Override
    public void onError(Exception e) {
        log.info("[websocket] 连接错误={}", e.getMessage());
    }

}