<?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\AccessBundle\Database;

use Sso\WebserviceBundle\Security\Authentication\Token\WsFirewallToken;
use Doctrine\ORM\EntityManagerInterface;
use Sso\AccessBundle\Entity\AccessLog;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

/**
 * Class Manager
 * @package Sso\AccessBundle\Database
 */
class Manager
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    private $accessLogRepos;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var TokenStorage
     */
    private $security;

    /**
     * @var string
     */
    private $username = 'not set yet';

    /**
     * Manager constructor.
     * @param EntityManagerInterface $entityManager
     * @param LoggerInterface $logger
     * @param TokenStorage $security
     */
    public function __construct(EntityManagerInterface $entityManager, LoggerInterface $logger, TokenStorage $security)
    {
        $this->entityManager = $entityManager;
        $this->accessLogRepos = $this->entityManager->getRepository(AccessLog::class);
        $this->logger = $logger;
        $this->security = $security;
    }

    /**
     * Fast delete for whole access log
     */
    public function truncateWebserviceAccessLog()
    {
        $classMeta = $this->entityManager->getClassMetadata(AccessLog::class);
        $connection = $this->entityManager->getConnection();
        $dbPlatform = $connection->getDatabasePlatform();
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $connection->executeUpdate($dbPlatform->getTruncateTableSql($classMeta->getTableName()));
        $connection->query('SET FOREIGN_KEY_CHECKS=1');
    }

    /**
     * @param Request $request
     */
    public function logWebservicesAccess(Request $request)
    {
        $securityToken = $this->security->getToken();
        if ($securityToken) {
            $this->username = $securityToken->getUsername();
        }

        $serviceToken = 'not set';
        if ($securityToken instanceof WsFirewallToken) {
            $serviceToken = $securityToken->serviceToken;
        }

        $service =
            $request->headers->get('api-controller', '') .
            $request->headers->get('api-action', '');

        $this->logger->info($this->username . ' - ' . $service);
        $this->saveAccessLog($serviceToken, $service);
    }

    /**
     * @param $serviceToken
     * @param $service
     */
    private function saveAccessLog($serviceToken, $service)
    {

        //first check if the username exists
        $searchArray = ['username' => $this->username, 'token' => $serviceToken];
        $accessLog = $this->accessLogRepos->findOneBy(['username' => $this->username, 'token' => $serviceToken]);
        if (empty($accessLog)) {
            $accessLog = new AccessLog();
        }
        $accessLog->setUsername($this->username);
        $accessLog->setToken($serviceToken);
        $accessLog->addService($service);
        $accessLog->setUpdatedAt();

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

        return;
    }

    /**
     * @return \Doctrine\Common\Persistence\ObjectRepository
     */
    public function getAccessLogRepos()
    {
        return $this->accessLogRepos;
    }
}
