package com.alterdekim.hearthhack.component;

import com.alterdekim.hearthhack.entity.RoomPlayer;
import com.alterdekim.hearthhack.service.RoomPlayerService;
import com.alterdekim.hearthhack.service.RoomService;
import com.alterdekim.hearthhack.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class GamePool {

    @Autowired
    private UserService userService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomPlayerService roomPlayerService;

    private ConcurrentHashMap<Long, GameRoom> games = new ConcurrentHashMap<>();

    private static final int PLAYERS_COUNT = 2;

    @Scheduled(fixedRate = 1000)
    private void refreshRooms() {
        roomService.getAll()
                .forEach(r -> {
                    if( roomPlayerService.findByRoomId(r.getId()).size() != PLAYERS_COUNT ) return;
                    List<RoomPlayer> players = roomPlayerService.findByRoomId(r.getId());
                    roomPlayerService.removeByRoomId(r.getId());
                    roomService.removeRoom(r.getId());
                    games.put(r.getId(), new GameRoom(players, userService));
                });
    }

    public Boolean containsPlayer(Long userId) {
        return games.keySet()
                .stream()
                .anyMatch(k -> games.get(k)
                        .getPlayers()
                        .stream()
                        .anyMatch(p -> p.getId().longValue() == userId.longValue()
                        )
                );
    }

    public Optional<Long> getGameIdByPlayerId(Long userId) {
        return games.keySet()
                .stream()
                .filter(k -> games.get(k)
                        .getPlayers()
                        .stream()
                        .anyMatch(p -> p.getId().longValue() == userId.longValue()
                        )
                )
                .findFirst();
    }
}
