<?php

/**
 * Class Index
 *
 * 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  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Webservices\ObjectBundle\Database\Data\Object;

use Doctrine\Bundle\DoctrineBundle\Registry as DoctrineRegistry;
use Doctrine\ORM\EntityManager;
use Sso\Webservices\ObjectBundle\Entity\Object as EntityObject;
use Sso\Webservices\ObjectBundle\Database\Repository\Factory as RepositoryFactory;

/**
 * Class Index
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\Webservices\ObjectBundle\Database\Data\Object
 */
class Index
{

    /**
     * Doctrine Registry
     *
     * @var DoctrineRegistry
     */
    protected $doctrineRegistry;

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

    /**
     * @var RepositoryFactory
     */
    protected $repositoryFactory;

    /**
     * @param DoctrineRegistry $doctrineRegistry
     * @param RepositoryFactory $repoFactory
     */
    public function __construct(DoctrineRegistry $doctrineRegistry, RepositoryFactory $repoFactory)
    {
        $this->doctrineRegistry = $doctrineRegistry;
        $this->entityManager = $this->doctrineRegistry->getManager('Webservice');
        $this->repositoryFactory = $repoFactory;
    }

    /**
     * Persist and flush entity
     *
     * @param EntityObject $entity
     */
    public function save(EntityObject $entity)
    {
        $this->entityManager->persist($entity);
        $this->entityManager->flush($entity);
    }

    /**
     * Remove and flush entity
     *
     * @param EntityObject $entity
     */
    public function delete(EntityObject $entity)
    {
        $this->entityManager->remove($entity);
        $this->entityManager->flush($entity);
    }

    /**
     * Find all entities
     *
     * @return array
     */
    public function findAll()
    {
        return $this->repositoryFactory->object()->findAll();
    }

    /**
     * Find by method
     *
     * @param array $criteria
     * @param array $orderBy
     * @param int $limit
     * @param int $offset
     * @return array
     */
    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        return $this->repositoryFactory->object()->findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * Get count of all existing entities
     *
     * @return int
     */
    public function getCount()
    {
        return $this->repositoryFactory->object()->createQueryBuilder('b')
            ->select('count(b.guid)')
            ->getQuery()
            ->getSingleScalarResult();
    }

}
