<?php

/**
 * ServiceProviders service database handler
 *
 * 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       http://www.life-style.de
 */

namespace Sso\ApiBundle\Database\ServiceProvider;

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

/**
 * ServiceProviders service database handler
 */
class Service extends Base
{
    /**
     * List of all services
     *
     * @return array
     */
    public function getAll()
    {
        return $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service')->findAll();
    }

    /**
     * List of all services
     * @return array
     */
    public function getOneById($serviceId)
    {
        return $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service')
            ->findOneBy(['ServiceId' => $serviceId]);
    }

    /**
     *
     * @param string $ServiceToken
     * @param string $controllerName
     * @param string $actionName
     * @return ServiceProviderService|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;
    }


    /**
     * @param $serviceNameId
     * @return array
     */
    public function getByServiceNameId($serviceNameId)
    {
        $dql = 'SELECT a FROM LifeStyle\Tools\CredentialsBundle\Entity\Service a '
            . 'JOIN a.ServiceNames sn '
            . 'WHERE sn.ServiceNameId=:ServiceNameId ';
        $query = $this->_entityManager->createQuery($dql);

        $query->setParameters(array(
            'ServiceNameId' => (string)$serviceNameId
        ));

        return $query->getResult();
    }

    /**
     * @param $serviceNameId
     * @return array
     */
    public function getNotAssignedByServiceNameId($serviceNameId)
    {
        $allServices = $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service')->findAll();

        // filter out all services that currently do not have the given ServiceNameId assigned to them
        $services = [];
        foreach ($allServices as $aService) {
            if ($aService->getServiceNames()->count() == 0) {
                $services[] = $aService;
            } else {
                $hasServiceNameId = false;
                foreach ($aService->getServiceNames() as $serviceServiceName) {
                    if ($serviceServiceName->getServiceNameId() == $serviceNameId) {
                        $hasServiceNameId = true;
                    }
                }
                if (!$hasServiceNameId) {
                    $services[] = $aService;
                }
            }
        }

        return $services;
    }

    /**
     * @param string $serviceId
     * @param string $serviceNameId
     * @return bool
     */
    public function addToServiceName($serviceId, $serviceNameId)
    {
        if ((null === $serviceId) || (null === $serviceNameId)) {
            return false;
        }

        $serviceName = $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\ServiceName')->findOneBy(['ServiceNameId' => $serviceNameId]);
        $service = $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service')->findOneBy(['ServiceId' => $serviceId]);
        $serviceName->addService($service);
        $this->_entityManager->persist($serviceName);
        $this->_entityManager->flush();
        return true;
    }

    /**
     * @param string $serviceId
     * @param string $serviceNameId
     * @return bool
     */
    public function removeFromServiceName($serviceId, $serviceNameId)
    {
        $serviceName = $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\ServiceName')->findOneBy(['ServiceNameId' => $serviceNameId]);
        $service = $this->_entityManager->getRepository('LifeStyle\Tools\CredentialsBundle\Entity\Service')->findOneBy(['ServiceId' => $serviceId]);
        $serviceName->removeService($service);
        $this->_entityManager->persist($serviceName);
        $this->_entityManager->flush();
        return true;
    }
}
