<?php

namespace Cobblestone\CcLogin\Service;

use Exception;
use Doctrine\ORM\EntityManagerInterface;
use Cobblestone\CcLogin\Security\CCUser;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class RoleService extends AbstractCCService
{

    /**
     * @var EntityManagerInterface
     */
    protected $entityManager;
    /**
     * @var TokenStorageInterface
     */
    protected $tokenStorage;

    /**
     * RoleService constructor.
     * @param EntityManagerInterface $entityManager
     * @param TokenStorageInterface $tokenStorage
     * @param string $apiUrl
     */
    public function __construct(EntityManagerInterface $entityManager, TokenStorageInterface $tokenStorage, string $apiUrl)
    {
        $this->entityManager = $entityManager;
        $this->tokenStorage = $tokenStorage;
        parent::__construct($apiUrl);
    }

    /**
     * @param string $token
     * @param $applicationId
     * @return array|null
     * @throws Exception
     */
    public function getRoles(string $token, $applicationId)
    {
        return $this->callURMService( "/me/${applicationId}/role", $token);
    }

    public function getUserAccessibleRoles()
    {
        /** @var CCUser $user */
        $user = $this->tokenStorage->getToken()->getUser();
        if ($user) {
            return $user->getAssetRoles();
        }
        return [];
    }

    /**
     * @return array
     */
    public function getUserAccessibleRoleIds(): array {
        $roleIds = array_map(function ($role) {
            return $role['roleId'];
        }, $this->getUserAccessibleRoles());

        return $roleIds;
    }

    public function getAssetRoleId($assetId) {
        $roleArray = array_filter($this->getUserAccessibleRoles(), function ($roleArray) use ($assetId) {
            return ($roleArray['assetId'] == $assetId);
        });

        return reset($roleArray)['roleId'];
    }
}
