package com.jxy.marketall.Therad;

import com.alibaba.fastjson.JSONObject;
import com.jxy.common.core.utils.StringUtils;
import com.jxy.common.core.web.Result.AjaxResult;
import com.jxy.marketall.dto.BiAnAppWSDto;
import com.jxy.marketall.dto.BiAnWSDto;
import com.jxy.marketall.utils.AppWebSocketClient;
import com.jxy.marketall.websocket.AppWebSocketService;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description TODO
 * @Date 2022/6/30 18:49
 * @Author 杜懿
 */
public class AppSocketThread implements Runnable {

    private Logger log = LoggerFactory.getLogger(AppSocketThread.class);

    private AppWebSocketService appWebSocketService;
    private AppWebSocketClient appWebSocketClient = new AppWebSocketClient();

    public AppSocketThread(AppWebSocketService appWebSocketService) {
        this.appWebSocketService = appWebSocketService;
    }

    @Override
    public void run() {

        String url = "wss://fstream.binance.com/ws/btcusdt@kline_1d";
        WebSocketClient client = appWebSocketClient.getWS(url);
        try {
            BiAnAppWSDto biAn = null;
            while (!Thread.currentThread().isInterrupted()){
                //获取实时数据
                //biAn = UstreamTask.getRealData("btcusdt1d");
                biAn = appWebSocketClient.getData();
                if(StringUtils.isNotNull(biAn)){
                    try {
                        appWebSocketService.sendMessage(appWebSocketService.getUserName(),JSONObject.toJSONString(AjaxResult.success(biAn)));
                    }catch (Exception e){
                        //client.close();
                    }
                }else {
                }
                Thread.sleep(1000);
            }
            //client.close();

        }catch (InterruptedException e){
            e.printStackTrace();
            //client.close();
            Thread curr = Thread.currentThread();
            //再次调用interrupt方法中断自己，将中断状态设置为“中断”
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            curr.interrupt();
        }
    }


}
