<?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  2017 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\AccessBundle\Database;

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
     * @throws \Doctrine\DBAL\DBALException
     * @return void
     */
    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)
    {
        $xmlRequest = $request->attributes->get('XmlRequest');

        try {
            $this->username = (string)$xmlRequest->Credentials->ServiceTrigger->Username;
        } catch (\Exception $exception) {
            $this->username = 'not set';
        }

        try {
            $serviceToken = (string)$xmlRequest->Credentials->ServiceProvider->ServiceToken;
        } catch (\Exception $exception) {
            $serviceToken = 'not set';
        }

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

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

    /**
     * @param string $serviceToken
     * @param string $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;
    }
}
