<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Components\Offer;

use Contao\CoreBundle\Filesystem\FilesystemItem;
use Contao\CoreBundle\Filesystem\FilesystemItemIterator;
use Contao\CoreBundle\Filesystem\SortMode;
use Contao\CoreBundle\Filesystem\VirtualFilesystemInterface;
use Ferienpass\CoreBundle\Entity\Dbafs;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent(template: '@FerienpassAdmin/components/Offer/ImagePicker.html.twig', route: 'live_component_admin')]
class ImagePicker extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    #[LiveProp(writable: true)]
    public ?string $selectedMediaUuid = null;

    #[LiveProp]
    public ?string $name = null;

    public function __construct(private readonly VirtualFilesystemInterface $mediaStorage)
    {
    }

    public function getMediaFiles(): FilesystemItemIterator
    {
        $listing = $this->mediaStorage->listContents('');

        return $listing
            ->filter(function (FilesystemItem $item): bool {
                if (!$item->isFile()) {
                    return false;
                }

                $meta = $item->getExtraMetadata();
                $model = $meta->get('model') ?? null;

                if (!$model instanceof Dbafs) {
                    return false;
                }

                return $this->isGranted('view', $model);
            })
            ->sort(SortMode::lastModifiedDescending);
    }

    #[LiveAction]
    public function select(#[LiveArg] string $uuid): void
    {
        $this->selectedMediaUuid = $uuid;
        $this->emitUp('imageSelected', [
            'uuid' => $uuid,
        ]);
    }
}
