<?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\Test;

use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\PermissionsGroup;
use Chill\MainBundle\Entity\RoleScope;
use Chill\MainBundle\Entity\User;

/**
 * A trait to prepare user with permission. May be used
 * within tests.
 *
 * **Usage : ** You must set up trait with `setUpTrait` before use
 * and use tearDownTrait after usage.
 *
 * @codeCoverageIgnore
 */
trait PrepareUserTrait
{
    /**
     * prepare a user with correct permissions.
     *
     * Example of permissions:
     * ```
     * array(
     *    array( 'center' => $centerA, 'permissionsGroup' => array(
     *        'role' => 'CHILL_REPORT_SEE', 'scope' => $scopeA
     *    ),
     *    array( 'center' => $centerB, 'permissionsGroup' => array(
     *        'role' => 'CHILL_ACTIVITY_UPDATE', 'scope' => $scopeB
     *    )
     * )
     * ```
     * Scope must be an int. Scope created have this int as id, and the
     * int converted to string as name.
     *
     * @param array $permissions an array of permissions, with key 'center' for the center and key 'attrs' for an array of  ['role' => (string), 'scope' => (int)]
     *
     * @return User
     *
     * @throws \LogicException if the trait is not set up
     */
    protected static function prepareUser(array $permissions)
    {
        $user = new User();

        foreach ($permissions as $permission) {
            $groupCenter = (new GroupCenter())
                ->setCenter($permission['center']);
            $permissionGroup = new PermissionsGroup();

            foreach ($permission['permissionsGroup'] as $pg) {
                $roleScope = (new RoleScope())
                    ->setRole($pg['role'])
                    ->setScope($pg['scope']);

                $permissionGroup->addRoleScope($roleScope);
            }

            $groupCenter->setPermissionsGroup($permissionGroup);
            $user->addGroupCenter($groupCenter);
        }

        return $user;
    }
}
