<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

#[ORM\Entity]
#[ORM\Cache(usage: 'NONSTRICT_READ_WRITE', region: 'acl_cache_region')]
#[ORM\Table(name: 'permission_groups')]
class PermissionsGroup
{
    /**
     * @var string[]
     */
    #[ORM\Column(type: \Doctrine\DBAL\Types\Types::JSON, options: ['default' => '[]', 'jsonb' => true])]
    private array $flags = [];

    /**
     * @var Collection<int, GroupCenter>
     */
    #[ORM\OneToMany(mappedBy: 'permissionsGroup', targetEntity: GroupCenter::class)]
    private Collection $groupCenters;

    #[ORM\Id]
    #[ORM\Column(name: 'id', type: \Doctrine\DBAL\Types\Types::INTEGER)]
    #[ORM\GeneratedValue(strategy: 'AUTO')]
    private ?int $id = null;

    #[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255, nullable: false, options: ['default' => ''])]
    private string $name = '';

    /**
     * @var Collection<int, RoleScope>
     */
    #[ORM\ManyToMany(targetEntity: RoleScope::class, inversedBy: 'permissionsGroups', cascade: ['persist'])]
    #[ORM\Cache(usage: 'NONSTRICT_READ_WRITE')]
    private Collection $roleScopes;

    /**
     * PermissionsGroup constructor.
     */
    public function __construct()
    {
        $this->roleScopes = new ArrayCollection();
        $this->groupCenters = new ArrayCollection();
    }

    public function addRoleScope(RoleScope $roleScope)
    {
        $this->roleScopes->add($roleScope);
    }

    /**
     * @return string[]
     */
    public function getFlags()
    {
        return $this->flags;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function getRoleScopes(): ArrayCollection|Collection
    {
        return $this->roleScopes;
    }

    /**
     * Test that a role scope is associated only once
     * with the permission group.
     */
    public function isRoleScopePresentOnce(ExecutionContextInterface $context)
    {
        $roleScopesId = array_map(
            static fn (RoleScope $roleScope) => $roleScope->getId(),
            $this->getRoleScopes()->toArray()
        );
        $countedIds = array_count_values($roleScopesId);

        foreach ($countedIds as $id => $nb) {
            if (1 < $nb) {
                $context->buildViolation('A permission is already present '
                        .'for the same role and scope')
                    ->addViolation();
            }
        }
    }

    /**
     * @throws \RuntimeException if the roleScope could not be removed
     */
    public function removeRoleScope(RoleScope $roleScope)
    {
        $result = $this->roleScopes->removeElement($roleScope);

        if (false === $result) {
            throw new \RuntimeException(sprintf("The roleScope '%s' could not be removed, ".'aborting.', spl_object_hash($roleScope)));
        }
    }

    /**
     * @return $this
     */
    public function setFlags(array $flags)
    {
        $this->flags = $flags;

        return $this;
    }

    /**
     * @return $this
     */
    public function setName(string $name)
    {
        $this->name = $name;

        return $this;
    }
}
