<?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\Database\ServiceProvider;

use \Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Validator\ValidatorInterface as Validator;

/**
 * Class Manager
 * @package Sso\WebserviceBundle\Database\ServiceProvider
 */
class Manager
{
    /**
     * Entity manager
     * @var \Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    /**
     * Validator
     * @var Validator
     */
    protected $validator;

    /**
     * @var boolean
     */
    private $readonly;

    /**
     * List of databases
     * @var array
     */
    protected $_db = array();

    /**
     * Manager constructor.
     * @param EntityManager $entityManager
     * @param Validator $validator
     * @param bool $readonly
     */
    public function __construct(EntityManager $entityManager, Validator $validator, $readonly)
    {
        $this->entityManager = $entityManager;
        $this->validator = $validator;
        $this->readonly = $readonly;
    }

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\Token
     */
    public function token()
    {
        return $this->_getDatabase('Token');
    }

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\TokenUsage
     */
    public function tokenUsage()
    {
        return $this->_getDatabase('TokenUsage');
    }

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\Service
     */
    public function service()
    {
        return $this->_getDatabase('Service');
    }

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\ServiceName
     */
    public function serviceName()
    {
        return $this->_getDatabase('ServiceName');
    }

    /**
     * @return \Sso\WebserviceBundle\Database\ServiceProvider\Log
     */
    public function log()
    {
        return $this->_getDatabase('Log');
    }

    /**
     * @param string $class
     * @return Base Database
     */
    protected function _getDatabase($class)
    {
        $class = __NAMESPACE__ . '\\' . $class;
        return isset($this->_db[$class]) ? $this->_db[$class] : ($this->_db[$class] = new $class($this->entityManager, $this->validator, $this->readonly));
    }
}
