<?php

namespace App\Game\Service;

use App\Game\Entity\Game;
use App\Game\Entity\Player;
use App\Game\Enum\SessionSettingType;
use App\Game\Enum\SessionStatus;
use App\Game\Repository\PlayerRepository;
use App\Game\Repository\SessionSettingRepository;
use App\Tech\Entity\User;
use Doctrine\ORM\EntityManagerInterface;

class PlayerService
{
    public function __construct(
        private PlayerRepository $playerRepository,
        private SessionSettingRepository $sessionSettingRepository,
        private EntityManagerInterface $entityManager,
    ) {
    }

    public function GetCurrentlyActiveAsPlayer(User $user): ?Player
    {
        $player = $this->playerRepository->createQueryBuilder('p')
            ->join('p.session', 's')
            ->where('p.user = :user')
            ->andWhere('s.status IN (:statuses)')
            ->setParameter('user', $user)
            ->setParameter('statuses', [
                SessionStatus::READY,
                SessionStatus::PLAYING,
            ])
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();

        return $player;
    }

    public function getCurrentPwdOfPlayer(Player $player) : ?string {
        $settingName = match($player->getScreen()) {
            1 => SessionSettingType::PWD_FOR_PLAYER1,
            2 => SessionSettingType::PWD_FOR_PLAYER2,
            3 => SessionSettingType::PWD_FOR_PLAYER3,
            default => null,
        };

        if (!$settingName) {
            return null;
        }

        $setting = $this->sessionSettingRepository->getSetting($player->getSession(), $settingName, $player);
        return $setting?->getValue();
    }

    public function saveCurrentPwdOfPlayer(Player $player, string $newLocation)
    {
        $settingName = match($player->getScreen()) {
            1 => SessionSettingType::PWD_FOR_PLAYER1,
            2 => SessionSettingType::PWD_FOR_PLAYER2,
            3 => SessionSettingType::PWD_FOR_PLAYER3,
            default => null,
        };

        if (!$settingName) {
            return;
        }

        $setting = $this->sessionSettingRepository->getSetting($player->getSession(), $settingName, $player);
        $setting->setValue($newLocation);

        $this->entityManager->persist($setting);
        $this->entityManager->flush();
    }
}
