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

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson2.JSONObject;
import com.huashe.park.common.DateTimeUtil;
import com.huashe.park.domain.dto.UWBAuth;
import com.huashe.park.infrastructure.cfg.forest.UWBForestCfg;
import com.huashe.park.infrastructure.cfg.mqtt.MqttCfg;
import com.huashe.park.infrastructure.uwb.UWBWebService;

import cn.hutool.core.map.MapUtil;

@Configuration
@ConditionalOnBean(UWBForestCfg.class)
public class UWBCfg {
    private static final Logger log = LoggerFactory.getLogger(UWBCfg.class);

    @Autowired
    private UWBForestCfg uwbForestCfg;

    @Resource
    private UWBWebService uwbWebService;

    @Bean
    @ConditionalOnBean(MqttCfg.class)
    @ConditionalOnProperty(havingValue = "true", name = "evt-fusion.uwb-tag-listener.enable")
    public UWBSocketClient uwbWebSocketClient() throws URISyntaxException {
        return new UWBSocketClient(new URI(uwbForestCfg.getUwbSocket()));
    }

    @Bean
    @ConditionalOnBean(MqttCfg.class)
    @ConditionalOnProperty(havingValue = "true", name = "evt-fusion.uwb-tag-listener.enable")
    public WebSocketClient webSocketClient(UWBSocketClient uwbWebSocketClient) {
        UWBAuth uwbAuth = authUWB();
        if (ObjectUtils.isEmpty(uwbAuth)) {
            return null;
        }
        uwbWebSocketClient.setAuthToken(uwbAuth);
        uwbWebSocketClient.connect();
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (uwbWebSocketClient.isClosed()) {
                    UWBAuth uwbAuth = authUWB();
                    if (ObjectUtils.isEmpty(uwbAuth)) {
                        return;
                    }
                    uwbWebSocketClient.setAuthToken(uwbAuth);
                    uwbWebSocketClient.reconnect();
                }
            }
        }, 1000, 5000);
        return uwbWebSocketClient;
    }

    private UWBAuth authUWB() {
        Map map = uwbWebService.exchangeToken(new HashMap<String, Object>() {
            {
                {
                    put("username", uwbForestCfg.getUwbUsr());
                    put("password", uwbForestCfg.getUwbPwd());
                    put("isfresh", 1);
                }
            }
        });
        Integer code = MapUtil.getInt(map, "code", 400);
        if (code != 200) {
            log.error("获取token失败");
            return null;
        }
        JSONObject data = MapUtil.get(map, "data", JSONObject.class);
        UWBAuth uwbAuth = new UWBAuth();
        String accessToken = data.getString("access_token");
        if (StringUtils.isBlank(accessToken)) {
            log.error("获取token失败{}", data);
            return null;
        }
        uwbAuth.setAccessToken(data.getString("access_token"));
        uwbAuth.setRegister(Long.toString(DateTimeUtil.timestampMillis()));
        return uwbAuth;
    }

}
