<?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\Webservice;

use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityRepository;
use Sso\WebserviceBundle\Entity\Webservice\Type\Role as ModelRole;
use Sso\WebserviceBundle\Entity\Webservice\Type\Application as ModelApplication;

/**
 * Class Role
 * @package Sso\WebserviceBundle\Database\Webservice
 */
class Role extends Base
{
    /**
     * Save role to database
     * @param ModelRole $typeRole
     * @return bool Returns true on success, false on validation failure
     */
    public function saveRole(ModelRole $typeRole)
    {
        // Do default validation
        $typeRole->setValidator($this->validator);
        if (!$typeRole->isValid()) {
            return false;
        }

        if ($this->readonly) {
            return false;
        }

        $this->entityManager->persist($typeRole);
        $this->entityManager->flush($typeRole);

        return true;
    }

    /**
     * Delete role from database
     * @param ModelRole $typeRole
     * @return bool True on success
     */
    public function deleteRole(ModelRole $typeRole)
    {
        $typeRole->setValidator($this->validator);
        if (!$typeRole->validate(array('ApplicationRole_Delete'))) {
            return false;
        }

        if ($this->readonly) {
            return false;
        }

        $this->entityManager->remove($typeRole);
        $this->entityManager->flush($typeRole);

        return true;
    }

    /**
     * Find role by id
     * @param string $roleId
     * @return ModelRole|null
     */
    public function getRoleById($roleId)
    {
        return $this->getRepository()->find($roleId);
    }

    /**
     * Get role by name
     * @param ModelApplication $application
     * @param string $roleName
     * @return ModelRole|null
     */
    public function getRoleByName(ModelApplication $application, $roleName)
    {
        $roleName = strtolower($roleName);
        foreach ($application->getRoles() as $role) {
            if ($role->getLowername() == $roleName) {
                return $role;
            }
        }
        return null;
    }

    /**
     * Find a list of applications roles by role-name
     * @param string $applicationId
     * @param string $roleName
     * @return ModelRole|null|array
     * @throws \Exception
     */
    public function getRolesByName($applicationId, $roleName, $limit = 1, $offset = 0)
    {
        $roleName = str_replace('%', '\%', strtolower($roleName));
        return $this->getRepository()
                ->createQueryBuilder('a')
                ->where('a.ApplicationId=:applicationId')
                ->andWhere('a.Lowername LIKE :rolename')
                ->setParameter('applicationId', $applicationId)
                ->setParameter('rolename', $roleName . '%')
                ->orderBy('a.Lowername')
                ->setMaxResults($limit)
                ->setFirstResult($offset)
                ->getQuery()
                ->getResult();
    }

    /**
     * @return ObjectRepository|EntityRepository
     */
    public function getRepository()
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\Role');
    }
}
