package com.caliverse.admin.domain.service;


import com.caliverse.admin.domain.RabbitMq.MessageHandlerService;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.code.ErrorCode;
import com.caliverse.admin.global.common.exception.RestApiException;
import com.caliverse.admin.redis.service.RedisUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserGameSessionService {

    private final RedisUserInfoService redisUserInfoService;
    //private final RabbitMqService rabbitMqService;

    private final MessageHandlerService messageHandlerService;


    public  UserGameSessionService(RedisUserInfoService redisUserInfoService
                                   , MessageHandlerService messageHandlerService
    ) {
        this.redisUserInfoService = redisUserInfoService;
        this.messageHandlerService = messageHandlerService;
    }


    public void kickUserSession(String userGuid){

        var loginSession = redisUserInfoService.getUserLoginSessionInfo(userGuid);

        //게임이 접속중 이면 kick 하고 2초 대기
        if(null != loginSession ){
            var serverName = loginSession.getCurrentServer();
            messageHandlerService.sendUserKickMessage(userGuid, serverName);

            //여기서 2초 정도 대기(게임 메모리 정리를 위해)
            try{
                Thread.sleep(2000);
            }
            catch (InterruptedException e){
                log.error("InterruptedException message: {}, serverName: {}, e.Message : {}", userGuid, serverName, e.getMessage());
                throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.EXCEPTION_INVALID_PROTOCOL_BUFFER_EXCEPTION_ERROR.getMessage());
            }
        }
    }
}
