<?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 Sso\AccessBundle\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;
use Exception;

/**
 * Class TemporaryToken
 *
 * @ORM\Entity(repositoryClass="Sso\AccessBundle\Repository\TemporaryTokenRepository")
 * @ORM\Table(name="temporary_token", indexes={
 *      @ORM\Index(name="idx_temporary_token", columns={"expire"})
 * })
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package Sso\AccessBundle\Entity
 */
class TemporaryToken
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="user_identifier", type="string", length=255)
     * @var string
     */
    private $userIdentifier;

    /**
     * @ORM\Column(name="user_ids", type="simple_array")
     * @var array
     */
    private $userIds = [];

    /**
     * @ORM\Column(name="expire", type="datetime")
     * @var DateTime
     */
    private $expire;

    /**
     * TemporaryToken constructor.
     * @param string $userIdentifier
     * @throws Exception
     */
    public function __construct(string $userIdentifier)
    {
        $this->userIdentifier = $userIdentifier;
        $this->expire = new DateTime('+1 hour');
    }

    /**
     * @return string
     */
    public function getUserIdentifier(): string
    {
        return $this->userIdentifier;
    }

    /**
     * @return array
     * @throws Exception
     */
    public function getUserIds(): array
    {
        return $this->expire > new DateTime() ? $this->userIds : [];
    }

    /**
     * @param string $userId
     * @throws Exception
     */
    public function addUserId(string $userId): void
    {
        $this->expire = new DateTime('+1 hour');
        if (!in_array($userId, $this->userIds)) {
            $this->userIds[] = $userId;
        }
    }

    /**
     * @return DateTime
     */
    public function getExpire(): DateTime
    {
        return $this->expire;
    }
}
