<?php

namespace Ig\IgReservations\Service;

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

class UserService implements \TYPO3\CMS\Core\SingletonInterface
{
    protected Context $context;
    protected FeUserRepository $feUserRepository;

    public function __construct(FeUserRepository $feUserRepository)
    {
        $this->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 \Ig\IgReservations\Domain\Model\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');
    }
}
