<?php

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

namespace Sso\WebserviceBundle\Database\Webservice;

use Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy as PolicyEntity;
use Doctrine\ORM\EntityRepository;

/**
 * Class PasswordPolicies
 * @package Sso\WebserviceBundle\Database\Webservice
 */
class PasswordPolicy extends Base
{
    /**
     * @param $policyId
     * @return PolicyEntity|null|object
     */
    public function getOne($policyId)
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy')->findOneBy(
            ['policyId' => $policyId]
        );
    }

    /**
     * @param $policyId
     * @return PolicyEntity|null|object
     */
    public function getDefault()
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy')->findOneBy(
            ['isDefault' => 1]
        );
    }

    /**
     * @return PolicyEntity|null|object
     */
    public function getDefaultPolicy()
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy')->findOneBy(['isDefault' => true]);
    }

    /**
     * @return void
     */
    public function clearDefault()
    {
        $query = $this->entityManager->createQuery(
            'UPDATE Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy p SET p.isDefault=\'0\''
        );
        $query->execute();
    }

    /**
     * @return void
     */
    public function clearDefaultExcludeId($id)
    {
        $query = $this->entityManager->createQuery(
            "UPDATE Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy p SET p.isDefault='0' WHERE p.policyId != '$id'"
        );
        $query->execute();
    }

    /**
     * @return array
     */
    public function getChoiceList(){

        $policies = $this->entityManager->getRepository(
            'Sso\WebserviceBundle\Entity\Webservice\Type\PasswordPolicy'
        )->findAll();

        $policyChoiceList[''] = 'Please select a policy';
        foreach ($policies as $policy){
            $policyChoiceList[$policy->getPolicyId()] = $policy->getTitle();
        }
        return $policyChoiceList;
    }
}
