<?php
namespace verbb\base\twig;

use craft\base\Element as CraftElement;
use craft\base\Model;

use Closure;

use Twig\Markup;
use Twig\Sandbox\SecurityNotAllowedFilterError;
use Twig\Sandbox\SecurityNotAllowedFunctionError;
use Twig\Sandbox\SecurityNotAllowedMethodError;
use Twig\Sandbox\SecurityNotAllowedPropertyError;
use Twig\Sandbox\SecurityNotAllowedTagError;
use Twig\Sandbox\SecurityPolicyInterface;
use Twig\Template;

class SecurityPolicy implements SecurityPolicyInterface
{
    // Properties
    // =========================================================================

    private array $allowedTags = [];
    private array $allowedFilters = [];
    private array $allowedMethods = [];
    private array $allowedProperties = [];
    private array $allowedFunctions = [];


    // Public Methods
    // =========================================================================

    public function __construct(array $allowedTags = [], array $allowedFilters = [], array $allowedMethods = [], array $allowedProperties = [], array $allowedFunctions = [])
    {
        $this->allowedTags = $allowedTags;
        $this->allowedFilters = $allowedFilters;
        $this->setAllowedMethods($allowedMethods);
        $this->allowedProperties = $allowedProperties;
        $this->allowedFunctions = $allowedFunctions;
    }

    public function setAllowedTags(array $tags): void
    {
        $this->allowedTags = $tags;
    }

    public function setAllowedFilters(array $filters): void
    {
        $this->allowedFilters = $filters;
    }

    public function setAllowedMethods(array $methods): void
    {
        $this->allowedMethods = [];
        foreach ($methods as $class => $m) {
            $this->allowedMethods[$class] = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, \is_array($m) ? $m : [$m]);
        }
    }

    public function setAllowedProperties(array $properties): void
    {
        $this->allowedProperties = $properties;
    }

    public function setAllowedFunctions(array $functions): void
    {
        $this->allowedFunctions = $functions;
    }

    public function checkSecurity($tags, $filters, $functions): void
    {
        foreach ($tags as $tag) {
            if (!in_array($tag, $this->allowedTags)) {
                throw new SecurityNotAllowedTagError(sprintf('Tag "%s" is not allowed.', $tag), $tag);
            }
        }

        foreach ($filters as $filter) {
            if (!in_array($filter, $this->allowedFilters)) {
                throw new SecurityNotAllowedFilterError(sprintf('Filter "%s" is not allowed.', $filter), $filter);
            }
        }

        foreach ($functions as $function) {
            if (!in_array($function, $this->allowedFunctions)) {
                throw new SecurityNotAllowedFunctionError(sprintf('Function "%s" is not allowed.', $function), $function);
            }
        }
    }

    public function checkMethodAllowed($obj, $method): void
    {
        if ($obj instanceof Template || $obj instanceof Markup) {
            return;
        }

        $method = strtolower($method);

        foreach ($this->allowedMethods as $class => $methods) {
            if ($obj instanceof $class && in_array($method, $methods, true)) {
                return;
            }
        }

        $class = $obj::class;
        throw new SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method);
    }

    public function checkPropertyAllowed($obj, $property): void
    {
        foreach ($this->allowedProperties as $class => $properties) {
            if ($obj instanceof $class && $this->_isPropertyAllowed($obj, $property, $properties)) {
                return;
            }
        }

        if ($this->_isDefaultPropertyAllowed($obj, $property)) {
            return;
        }

        $class = $obj::class;
        throw new SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property);
    }

    // Private Methods
    // =========================================================================

    private function _isPropertyAllowed(object $obj, string $property, mixed $properties): bool
    {
        if ($properties instanceof Closure) {
            return (bool)$properties($obj, $property);
        }

        return in_array($property, is_array($properties) ? $properties : [$properties], true);
    }

    private function _isDefaultPropertyAllowed(object $obj, string $property): bool
    {
        if ($obj instanceof Model && in_array($property, $obj->attributes(), true)) {
            return true;
        }

        if ($obj instanceof CraftElement) {
            return $obj->getFieldLayout()?->getFieldByHandle($property) !== null;
        }

        return false;
    }
}
