<?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\TokenUsage as ModelTokenUsage;
use Sso\ApiBundle\Api\Exception\Type\Api as ApiException;

/**
 * Class TokenUsage
 * @package LifeStyle\Tools\CredentialsBundle\Database
 */
class TokenUsage extends Base
{
    /**
     * @var \LifeStyle\Tools\CredentialsBundle\Entity\TokenUsage
     */
    protected $usageModel;

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->getRepository()->findBy(array(), array('Date' => 'desc'));
    }

    /**
     * @param string $ipAddress
     */
    public function setIp($ipAddress)
    {
        $this->getModel()->setIp($ipAddress);
        $this->saveModel();
    }

    /**
     * @param string $controllerName
     */
    public function setController($controllerName)
    {
        $this->getModel()->setController($controllerName);
        $this->saveModel();
    }

    /**
     * @param string $actionName
     */
    public function setAction($actionName)
    {
        $this->getModel()->setAction($actionName);
        $this->saveModel();
    }

    /**
     * @param \ServiceProvider\Model\Type\Token $token
     */
    public function setToken($token)
    {
        $this->getModel()->setToken($token);
        $this->saveModel();
    }

    /**
     * Save current model
     */
    protected function saveModel()
    {
        $model = $this->getModel();

        if ($model->isValid()) {
            $this->saveTokenUsage($model);
        }
    }

    /**
     * Get token usage model
     *
     * @return \ServiceProvider\Model\Type\TokenUsage
     */
    protected function getModel()
    {
        if (null === $this->usageModel) {
            $this->usageModel = new ModelTokenUsage();
            $this->usageModel->initUsageId();
            $this->usageModel->setDate(new \DateTime());
            $this->usageModel->setTrackId(ApiException::getTrackId());
        }
        return $this->usageModel;
    }

    /**
     * Save token usage model
     *
     * @param ModelTokenUsage $modelTokenUsage
     */
    public function saveTokenUsage(ModelTokenUsage $modelTokenUsage)
    {
        $this->entityManager->persist($modelTokenUsage);
        $this->entityManager->flush($modelTokenUsage);
    }

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