<?php

namespace Ig\IgReservations\ViewHelpers\Calendar;

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

class HasPermissionViewHelper extends AbstractConditionViewHelper
{
    /**
     * Initialize arguments
     */
    public function initializeArguments()
    {
        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);
    }

    /**
     * This method decides if the condition is TRUE or FALSE. It can be overriden in extending viewhelpers
     * to adjust functionality.
     *
     * @param array $arguments ViewHelper arguments to evaluate the condition for this ViewHelper, allows for
     *                         flexiblity in overriding this method.
     * @return bool
     */
    protected static function evaluateCondition($arguments = null)
    {
        $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;
    }
}
