<?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 LifeStyle\Tools\RestAuthBundle\Api\Database;

use Doctrine\Bundle\DoctrineBundle\Registry as DoctrineRegistry;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use LifeStyle\Tools\RestAuthBundle\Api;
use LifeStyle\Tools\RestAuthBundle\Entity\Usage\WsseTokens as EntityWsseTokens;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * Class Index
 * @package LifeStyle\Tools\RestAuthBundle\Api\Database
 */
class Index
{
    /**
     * @var DoctrineRegistry
     */
    protected $doctrineRegistry;

    /**
     * @var EntityManager
     */
    protected $emWs;

    /**
     * @var Api\Manager
     */
    protected $apiM;

    /**
     * @param Api\Manager $apiM
     */
    public function __construct(Api\Manager $apiM)
    {
        $this->apiM = $apiM;
        $this->doctrineRegistry = $this->apiM->getContainer()->get('doctrine');
        $this->emWs = $this->doctrineRegistry->getManager('Backend');
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->emWs;
    }

    /**
     * @return DoctrineRegistry|object
     */
    public function getDoctrineRegistry()
    {
        return $this->doctrineRegistry;
    }

    /**
     * @return ObjectRepository
     */
    public function getTokenRespository()
    {
        return $this->doctrineRegistry->getRepository('LifeStyleToolsRestAuthBundle:ServiceToken', 'Backend');
    }

    /**
     * @return ObjectRepository
     */
    public function getWsseTokensRespository()
    {
        return $this->doctrineRegistry->getRepository('LifeStyleToolsRestAuthBundle:WsseTokens', 'ReadWrite');
    }

    /**
     * @param string $nonce
     * @param string $passwordDigest
     * @param string $created
     * @param string $username
     */
    public function saveWsseToken($nonce, $passwordDigest, $created, $username)
    {

        $entity = new EntityWsseTokens();
        $entity->setNonce($nonce);
        $entity->setPasswordDigest($passwordDigest);
        $entity->setRequestCreated($created);
        $entity->setUserName($username);

        $em = $this->doctrineRegistry->getManager('ReadWrite');
        $em->persist($entity);
        $em->flush($entity);
    }
}
