<?php

namespace Ig\IgReservations\Service;

use TYPO3\CMS\Core\SingletonInterface;
use Ig\IgReservations\Domain\Model\FeUser;
use Ig\IgReservations\Domain\Repository\FeUserRepository;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;

class UserService implements SingletonInterface
{
    protected Context $context;

    public function __construct(protected FeUserRepository $feUserRepository)
    {
        $this->context = GeneralUtility::makeInstance(Context::class);
    }

    /**
     * is the logged in user an admin?
     *
     * @return boolean
     */
    public function isLoggedIn()
    {
        return $this->context->getPropertyFromAspect('frontend.user', 'isLoggedIn');
    }

    /**
     * is the logged in user an admin?
     *
     * @return boolean
     */
    public function isAdminLoggedIn()
    {
        if (!$this->isLoggedIn()) {
            return false;
        }

        $userAspect = $this->context->getAspect('frontend.user');
        return in_array('reservations-admin', $userAspect->getGroupNames(), true);
    }

    /**
     * Returns the logged in user
     *
     * @return FeUser
     */
    public function getUser()
    {
        $userId = $this->context->getPropertyFromAspect('frontend.user', 'id');
        return $this->feUserRepository->findByUid($userId);
    }

    /**
     * Returns the id of the loggedin user
     *
     * @return int
     */
    public function getUserId()
    {
        return $this->context->getPropertyFromAspect('frontend.user', 'id');
    }
}
