<?php

/**
 * User: sb
 * Date: 14.11.2014
 * Time: 11:48
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH   * (Aschaffenburg, Germany)
 * and is protected 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  2014 Lifestyle Webconsulting GmbH
 * @version    $Id$
 * @link       www.life-style.de
 */

namespace Sso\ApiBundle\Database;

use Symfony\Component\Validator\Validator\RecursiveValidator as Validator;

/**
 * Database Manager
 */
class Manager
{

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

    /**
     * Doctrine Registry
     *
     * @var \Doctrine\Bundle\DoctrineBundle\Registry
     */
    protected $_registry;

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

    /**
     * Construtor
     *
     * @param \Doctrine\Bundle\DoctrineBundle\Registry $registry
     */
    public function __construct(\Doctrine\Bundle\DoctrineBundle\Registry $registry, Validator $validator)
    {
        $this->_registry = $registry;
        $this->validator = $validator;
    }

    /**
     *
     * @return \Sso\ApiBundle\Database\Backend\Factory
     */
    public function backend()
    {
        return $this->_getDatabaseManager('Sso\BackendBundle\Database\Backend\Manager', 'Backend');
    }

    /**
     *
     * @return \Sso\ApiBundle\Database\Webservice\Manager
     */
    public function webservice()
    {
        return $this->_getDatabaseManager(__NAMESPACE__ . '\Webservice\Manager', 'Webservice');
    }

    /**
     *
     * @return \Sso\ApiBundle\Database\ServiceProvider\Manager
     */
    public function serviceProvider()
    {
        return $this->_getDatabaseManager(__NAMESPACE__ . '\ServiceProvider\Manager', 'ServiceProvider');
    }

    /**
     * Returns database manager
     *
     * @param string $class
     * @param string $entityManager Entity-Manager-Name
     * @return Base Database
     */
    protected function _getDatabaseManager($class, $entityManager)
    {
        return isset($this->_db[$class]) ? $this->_db[$class] : ($this->_db[$class] = new $class($this->_getEntityManager($entityManager),
            $this->validator));
    }

    /**
     *
     * @param string $entityManagerName
     * @return \Doctrine\ORM\EntityManager
     */
    protected function _getEntityManager($entityManagerName)
    {
        return $this->_registry->getManager($entityManagerName);
    }

}
