package com.game.business.websocket.client;

import com.game.business.config.GameEightConfig;
import com.game.business.config.GameSevenConfig;
import com.game.business.task.AppGameBettingTask;
import com.game.business.util.Common;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.util.Date;


@Component
@ClientEndpoint
public class GameEightClient {

    @Autowired
    private AppGameBettingTask appGameBettingTask;

    @OnOpen
    public void onOpen(Session session) throws Exception{
        System.out.println("game eight 游戏已连接 server");
        session.getBasicRemote().sendText("ping");
        Common.sessionMap.put(Common.GAME_EIGHT_CODE, session);
    }

    @OnClose
    public void onClose(Session session) throws Exception{
        System.out.println("game eight 游戏已断开 server：" + new Date());
        connect();
    }

    @OnError
    public void onError(Session session, Throwable throwable) throws Exception{
        System.out.println("game eight 连接异常 [" + throwable.getMessage() + "]");
        connect();
    }

    public void connect(){
        synchronized (this){
            try {
                GameEightConfig.webSocketConnent.connect();
            }catch (Exception e){
                System.out.println("连接 game eight [socket] 异常" + e.getMessage());
            }
        }
    }

    @OnMessage
    public void onMessage(Session session, String message){
        try {
            if(StringUtils.isBlank(message)){
                System.out.println("game eight 数据为空");
                return;
            }

            System.out.println("game eight 接收数据" + message);

            if(message.equals("pong")){
                return;
            }

            appGameBettingTask.gameDataTask(message, Common.GAME_EIGHT_CODE);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("game eight 接收数据异常[" + e.getMessage() + "]");
        }
    }
}
