<?php

/**
 * 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  2018 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace LifeStyle\Tools\CredentialsBundle\Database;

use LifeStyle\Tools\CredentialsBundle\Entity\Service as ServiceModel;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\NonUniqueResultException;

/**
 * Class Service
 * @package LifeStyle\Tools\CredentialsBundle\Database
 */
class Service extends Base
{

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->getRepository()->findAll();
    }

    /**
     * @param string $ServiceToken
     * @param string $controllerName
     * @param string $actionName
     * @return ServiceModel|null
     * @throws \Exception
     */
    public function credentialsCheckTokenToControllerAndAction($ServiceToken, $controllerName, $actionName)
    {
        $dql = 'SELECT s FROM LifeStyle\Tools\CredentialsBundle\Entity\Service s '
            . 'JOIN s.ServiceNames sn '
            . 'JOIN sn.Tokens t '
            . 'WHERE t.ServiceToken=:ServiceToken '
            . 'AND sn.ServiceActive=:ServiceActive '
            . 'AND s.ServiceController=:ServiceController '
            . 'AND s.ServiceAction=:ServiceAction';
        $query = $this->entityManager->createQuery($dql);
        $query->setParameters(array(
            'ServiceToken' => (string)$ServiceToken,
            'ServiceActive' => 1,
            'ServiceController' => (string)$controllerName,
            'ServiceAction' => (string)$actionName,
        ));

        try {
            $serviceModel = $query->getSingleResult();
        } catch (\Exception $e) {

            // Service not found or too many rows
            if ($e instanceof NoResultException || $e instanceof NonUniqueResultException) {
                return null;
            }

            // An unexpected error
            throw $e;
        }

        return $serviceModel;
    }

    /**
     * @return \Doctrine\ORM\EntityRepository
     */
    public function getRepository()
    {
        return $this->entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service');
    }
}
