<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Redis;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class RedisConnectionFactory implements EventSubscriberInterface
{
    private readonly string $host;

    private readonly int $port;

    private readonly ChillRedis $redis;

    private readonly int $timeout;

    public function __construct($parameters)
    {
        $this->host = $parameters['host'];
        $this->port = (int) $parameters['port'];
        $this->timeout = (int) $parameters['timeout'];
        $this->redis = new ChillRedis();
    }

    public function create()
    {
        $result = $this->redis->connect($this->host, $this->port, $this->timeout);

        if (false === $result) {
            throw new \RuntimeException('Could not connect to redis instance');
        }

        return $this->redis;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            'kernel.finish_request' => [
                ['onKernelFinishRequest'],
            ],
        ];
    }

    public function onKernelFinishRequest()
    {
        $this->redis->close();
    }
}
