<?php

namespace Ig\IgReservations\ViewHelpers\Calendar;

use Ig\IgReservations\Domain\Model\Calendar;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractConditionViewHelper;

class HasPermissionViewHelper extends AbstractConditionViewHelper
{
    /**
     * Initialize arguments
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('permission', 'string', 'permission to test', true);
        $this->registerArgument('allowAdmin', 'bool', 'also grant access to admin', false, false);
        $this->registerArgument('calendar', Calendar::class, 'Calendar for ACL', true);
    }

    /**
     * Static method which can be overridden by subclasses. If a subclass
     * requires a different (or faster) decision then this method is the one
     * to override and implement.
     *
     * @param array<string, mixed> $arguments
     * @param RenderingContextInterface $renderingContext
     * @return bool
     */
    public static function verdict(array $arguments, RenderingContextInterface $renderingContext): bool
    {
        $calendar = $arguments['calendar'];
        $permissions = explode(',', (string) $arguments['permission']);
        $acl = $calendar->getAcl();

        if (!$acl) {
            return false;
        }
        if ($arguments['allowAdmin'] && $acl->getIsAdmin()) {
            return true;
        }
                                                            
        foreach ($permissions as $permission) {
            if ($acl->hasPermission($permission)) {
                return true;
            }
        }
        return false;
    }
}
