package com.game.business.websocket.client;

import com.game.business.config.GameOneConfig;
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 GameOneClient {

    @Autowired
    private AppGameBettingTask appGameBettingTask;

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

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

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

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

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

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

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

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