import type { UUID } from '@/application/types' import { BaseEvent } from '@/application/base/baseEvent' import { SocketEvent } from '@/application/enums' import MapManager from '@/managers/mapManager' import CharacterHairRepository from '@/repositories/characterHairRepository' import CharacterRepository from '@/repositories/characterRepository' import TeleportService from '@/services/characterTeleportService' interface CharacterConnectPayload { characterId: UUID characterHairId?: UUID } export default class CharacterConnectEvent extends BaseEvent { private readonly characterHairRepository = new CharacterHairRepository() private readonly characterRepository = new CharacterRepository() public listen(): void { this.socket.on(SocketEvent.CHARACTER_CONNECT, this.handleEvent.bind(this)) } private async handleEvent(data: CharacterConnectPayload, callback: (response: any) => void): Promise { try { if (await this.checkForActiveCharacters()) { this.emitError('You are already connected to another character') return } const character = await this.characterRepository.getByUserAndId(this.socket.userId!, data.characterId) if (!character) { this.emitError('Character not found or does not belong to this user') return } // Set character id this.socket.characterId = character.id // Set character hair if (data.characterHairId !== undefined && data.characterHairId !== null) { const characterHair = await this.characterHairRepository.getById(data.characterHairId) await character.setCharacterHair(characterHair).save() } // Emit character connect event callback({ character }) // wait 300 ms, @TODO: Find a better way to do this, race condition await new Promise((resolve) => setTimeout(resolve, 500)) await TeleportService.teleportCharacter(character.id, { targetMapId: character.map.id, targetX: character.positionX, targetY: character.positionY, rotation: character.rotation, isInitialJoin: true, character }) } catch (error) { this.handleError('Failed to connect character', error) } } private async checkForActiveCharacters(): Promise { const characters = await this.characterRepository.getByUserId(this.socket.userId!) return characters?.some((char) => MapManager.getCharacterById(char.id)) ?? false } }