<?php

namespace KupShop\ArticlesBundle\Twig\Components\Articles;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ContentBundle\Util\ImageLocator;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\Functional\Mapping;
use KupShop\KupShopBundle\Util\System\PathFinder;
use Query\Operator;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Articles/components/Articles/PressroomGallery/PressroomGallery.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class PressroomGallery extends BaseComponent
{
    public array $photos;

    private ?array $photosHash = null;

    public function __construct(
        private readonly PathFinder $pathFinder,
        private readonly ImageLocator $imageLocator,
    ) {
    }

    public function getIsUserLoggedIn()
    {
        return Contexts::get(UserContext::class)->isActive();
    }

    public function getIsPressroomUser()
    {
        return Contexts::get(UserContext::class)->isType('pressroom');
    }

    public function createThumbnailFromPhoto(array $photo): Thumbnail
    {
        return new Thumbnail($photo['id'], $photo['descr'], $photo['date_update']);
    }

    public function getPhotoOriginalPath(array $photo): string
    {
        // use special route to handle download of the original, unprocessed image
        return path('kupshop_catalog_image_photosoriginal', ['photoId' => $photo['id'], 'hash' => $this->getPhotoHash($photo)]);
    }

    public function getPhotoFilesize(array $photo): int
    {
        $path = $this->pathFinder->dataPath('photos/'.$photo['source'].$photo['image_2']);

        if (file_exists($path) && ($filesize = filesize($path))) {
            return $filesize;
        }

        return 0;
    }

    private function getPhotoHash(array $photo): ?string
    {
        if ($this->photosHash === null) {
            $this->photosHash = Mapping::mapKeys(
                sqlQueryBuilder()
                    ->select('*')
                    ->from('photos')
                    ->where(Operator::inIntArray(array_map(fn ($x) => $x['id'], $this->photos), 'id'))
                    ->execute(),
                function ($k, $v) {
                    $image = $this->imageLocator->getImage($v);

                    return [$image->getId(), $image->getHash()];
                }
            );
        }

        return $this->photosHash[$photo['id']] ?? null;
    }
}
