package com.game.business.websocket;


import com.game.business.config.SpringContextSetting;
import com.game.business.util.Common;
import com.game.business.websocket.client.GameOneClient;

import javax.websocket.ContainerProvider;
import java.net.URI;

public class WebSocketConnent {

    private String WS_URL;
    private String WS_URL_NAME;
    private int WS_CONNENT_NUM = 0;
    private int WS_CONNENT_MAX_NUM = 10;

    public WebSocketConnent(String WS_URL, String WS_URL_NAME){
        this.WS_URL = WS_URL;
        this.WS_URL_NAME = WS_URL_NAME;
    }

    public void connect() throws Exception{
        while (true){
            try {
                System.out.printf("正在" + (this.WS_CONNENT_NUM == 0 ? "" : ("第" + this.WS_CONNENT_NUM + "次")) + "连接WebSocket[" + this.WS_URL_NAME + "]......");
                if(Common.GANME_ONE_NAME.equals(this.WS_URL_NAME)){
                    GameOneClient client = SpringContextSetting.getBean(GameOneClient.class);
                    ContainerProvider.getWebSocketContainer().connectToServer(client, new URI(this.WS_URL));
                }

                System.out.printf(this.WS_URL_NAME + " 已成功连接Websocket[" + this.WS_URL + "]");
                this.WS_CONNENT_NUM = 0;
                break;
            }catch (Exception e){
                if(this.WS_CONNENT_MAX_NUM > this.WS_CONNENT_NUM){
                    this.WS_CONNENT_NUM ++;
                }
                System.out.printf("连接[" + this.WS_URL_NAME + "]异常，" + this.WS_CONNENT_NUM + "秒后尝试重新连接：" + e.getMessage());
                Thread.sleep(this.WS_CONNENT_NUM * 1000);
            }
        }
    }
}
