<?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  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace SimpleSAML\Module\lifestyle\Auth;

use SimpleSAML\Auth\State;
use SimpleSAML\Error\BadRequest;
use SimpleSAML\Error\NoState;
use SimpleSAML\Module\core\Auth\UserPassBase;
use SimpleSAML\Module\lifestyle\Webservice\Handler;

/**
 * Class UserApplication
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package SimpleSAML\Module\lifestyle\Auth
 */
class UserApplication
{
    const APPLICATION_IDENTIFIER = 'application::';

    /**
     * @var string
     */
    private $authStateId;

    /**
     * Mfa constructor.
     * @param string $authStateId
     */
    private function __construct($authStateId)
    {
        $this->authStateId = $authStateId;
    }

    /**
     * @return UserApplication
     * @throws BadRequest
     */
    public static function createFromRequest()
    {
        if (!array_key_exists('AuthState', $_REQUEST)) {
            throw new BadRequest('Missing AuthState parameter.');
        }
        return new self($_REQUEST['AuthState']);
    }

    /**
     * @param string $username
     * @return array
     * @throws NoState
     */
    public function getApplications($username)
    {
        assert('is_string($username)');

        $state = State::loadState($this->authStateId, UserPassBase::STAGEID);

        if (!isset($state['SPMetadata']['attributes'])) {
            return [];
        }

        $applications = $this->findApplications($state['SPMetadata']['attributes']);
        if (!count($applications)) {
            return [];
        }

        /*
         * List of attributes may differ from service provider to service provider.
         * As the user-webservice only returns attributes for the current service provider,
         * the attribute-set is labeled with the current entity-id
         */
        $attributes = ['__entityid__' => $state['SPMetadata']['entityid']];

        $applicationNames = [];
        $userApplications = Handler::getUserApplicationAttributes($username, $applications);
        foreach ($userApplications as $applicationName => $userApplication) {
            $attributes[static::APPLICATION_IDENTIFIER . $applicationName][] = $userApplication->toString();
            $applicationNames[] = $userApplication->getName();
        }

        $attributes['applications'] = array_unique($applicationNames);

        return $attributes;
    }

    /**
     * @param array $attributes
     * @return array
     */
    private function findApplications($attributes)
    {
        $applicationNames = array();
        foreach ($attributes as $attribute) {
            if (0 === strpos($attribute, static::APPLICATION_IDENTIFIER)) {
                $applicationNames[] = substr($attribute, strlen(static::APPLICATION_IDENTIFIER));
            } elseif ('applications' === strtolower($attribute)) {
                $applicationNames[] = '*';
            }
        }
        return $applicationNames;
    }
}
