<?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\Token as TokenEntity;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\NonUniqueResultException;

/**
 * Class Token
 * @package LifeStyle\Tools\CredentialsBundle\Database
 */
class Token extends Base
{
    /**
     * @return array
     */
    public function getAll()
    {
        return $this->getRepository()->findAll();
    }

    /**
     * @param array $data
     */
    public function saveTokenFromArray($data)
    {
        $model = new ServiceProviderToken();
        $model->setServiceToken($data['ServiceToken']);
        $model->setServiceToken2Ip($data['ServiceToken2Ip']);
        $model->setAllowedCallsPerDay((int)$data['AllowedCallsPerDay']);
        $model->setValidUntil(new DateTime($data['ValidUntil']));
        $model->setBlocked((int)$data['Blocked']);

        $this->saveToken($model);
    }

    /**
     * Save token
     *
     * @param \LifeStyle\Tools\WebserviceBundle\Entity\ServiceProvider\Type\Token $model
     * @return boolean
     */
    public function saveToken(TokenEntity $model)
    {
        $this->entityManager->persist($model);
        $this->entityManager->flush($model);
    }

    public function deleteToken(ServiceProviderToken $model)
    {
        $this->entityManager->remove($model);
        $this->entityManager->flush($model);
    }

    /**
     *
     * @param string $ServiceToken
     * @return ServiceProviderToken|null
     * @throws \Exception
     */
    public function credentialsGetActiveToken($ServiceToken)
    {
        $dql = 'SELECT t FROM LifeStyle\Tools\CredentialsBundle\Entity\Token t '
            . 'WHERE t.ServiceToken=:ServiceToken '
            . 'AND t.Blocked=:Blocked '
            . 'AND t.ValidUntil>CURRENT_DATE()';
        $query = $this->entityManager->createQuery($dql);
        $query->setParameters(array(
            'ServiceToken' => (string)$ServiceToken,
            'Blocked' => 0,
        ));

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

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

            // An unexpected error
            throw $e;
        }
        return $tokenModel;
    }

    /**
     * Find user by token by id
     *
     * @param string $token
     * @return ModelToken|null
     */
    public function getTokenByToken($token)
    {
        return $this->getRepository()->findOneBy(array('ServiceToken' => $token));
    }

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

}
