<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Api;

use Sso\WebserviceBundle\Security\Authentication\Token\WsFirewallTokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Class AuthorizationManager
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Api
 */
class AuthorizationManager implements AuthorizationManagerInterface
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * AuthorizationManager constructor.
     * @param TokenStorageInterface $tokenStorage
     */
    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @param string $applicationName
     * @return bool
     */
    public function canReadApplication(string $applicationName): bool
    {
        return in_array($applicationName, $this->getUserRolesApplicationRead());
    }

    /**
     * @return array
     */
    public function getUserRolesApplicationRead(): array
    {
        $securityToken = $this->tokenStorage->getToken();
        if ($securityToken instanceof WsFirewallTokenInterface) {
            return $securityToken->getUserWsRolesRead();
        }

        return [];
    }

    /**
     * @param string $applicationName
     * @return bool
     */
    public function canWriteApplication(string $applicationName): bool
    {
        return in_array($applicationName, $this->getUserRolesApplicationWrite());
    }

    /**
     * @return array
     */
    public function getUserRolesApplicationWrite(): array
    {
        $securityToken = $this->tokenStorage->getToken();
        if ($securityToken instanceof WsFirewallTokenInterface) {
            return $securityToken->getUserWsRolesWrite();
        }

        return [];
    }
}
