<?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\WopiBundle\Service\Wopi;

use ChampsLibres\WopiLib\Contract\Entity\Document;
use ChampsLibres\WopiLib\Contract\Service\DocumentLockManagerInterface;
use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Entity\StoredObjectLock;
use Chill\DocStoreBundle\Entity\StoredObjectLockMethodEnum;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\Security\Core\Security;
use Webmozart\Assert\Assert;

final class ChillDocumentLockManager implements DocumentLockManagerInterface, EventSubscriberInterface
{
    private const LOCK_DURATION = 60 * 30;

    /**
     * Number of seconds to keep the lock after the delete lock operation.
     */
    private const LOCK_GRACEFUL_DURATION_TIME = 3;

    private bool $mustFlush = false;

    public function __construct(
        private readonly Security $security,
        private readonly EntityManagerInterface $entityManager,
        private readonly ClockInterface $clock,
        private readonly int $ttlAfterDeleteSeconds = self::LOCK_GRACEFUL_DURATION_TIME,
    ) {}

    public static function getSubscribedEvents(): array
    {
        return [TerminateEvent::class => 'onKernelTerminate'];
    }

    public function deleteLock(Document $document, RequestInterface $request): bool
    {
        Assert::isInstanceOf($document, StoredObject::class);

        foreach ($document->getLocks() as $lock) {
            if ($lock->isActiveAt($this->clock->now())) {
                $lock->setExpireAt($this->clock->now()->add(new \DateInterval('PT'.$this->ttlAfterDeleteSeconds.'S')));
                $this->mustFlush = true;
            }
        }

        return true;

    }

    public function getLock(Document $document, RequestInterface $request): string
    {
        Assert::isInstanceOf($document, StoredObject::class);

        foreach ($document->getLocks() as $lock) {
            if ($lock->isActiveAt($this->clock->now())) {
                return $lock->getToken();
            }
        }

        throw new \RuntimeException('wopi key does not exists');
    }

    public function hasLock(Document $document, RequestInterface $request): bool
    {
        Assert::isInstanceOf($document, StoredObject::class);

        foreach ($document->getLocks() as $lock) {
            if ($lock->isActiveAt($this->clock->now())) {
                return true;
            }
        }

        return false;
    }

    public function onKernelTerminate(TerminateEvent $event): void
    {
        if ($this->mustFlush) {
            $this->entityManager->flush();
        }
    }

    public function setLock(Document $document, string $lockId, RequestInterface $request): bool
    {
        Assert::isInstanceOf($document, StoredObject::class);
        $user = $this->security->getUser();

        if ($document->isLockedAt($this->clock->now())) {
            foreach ($document->getLocks() as $lock) {
                if ($lock->isActiveAt($this->clock->now())) {
                    $lock->setToken($lockId);
                    $lock->setExpireAt($this->clock->now()->add(new \DateInterval('PT'.self::LOCK_DURATION.'S')));
                    if ($user instanceof User) {
                        $lock->addUser($user);
                    }

                    $this->mustFlush = true;

                    return true;
                }
            }
        }

        // there is no lock yet, we must create one
        $lock = new StoredObjectLock(
            $document,
            method: StoredObjectLockMethodEnum::WOPI,
            createdAt: $this->clock->now(),
            token: $lockId,
            expireAt: $this->clock->now()->add(new \DateInterval('PT'.self::LOCK_DURATION.'S')),
        );

        if ($user instanceof User) {
            $lock->addUser($user);
        }

        $this->entityManager->persist($lock);
        $this->mustFlush = true;

        return true;
    }
}
