<?php

namespace Snaatch\Typo3\EventListener;

use Snaatch\Typo3\Backend\SnaatchContainerTrait;
use TYPO3\CMS\Backend\Form\Event\CustomFileControlsEvent;
use TYPO3\CMS\Core\Attribute\AsEventListener;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Page\JavaScriptModuleInstruction;

final class FileControlsEventListener
{
    use SnaatchContainerTrait;

    public function __construct(
        protected IconFactory $iconFactory
    ) {}

    #[AsEventListener]
    public function __invoke(CustomFileControlsEvent $event)
    {
        $this->addButton($event);
    }

    protected function addButton(CustomFileControlsEvent $event): void
    {
        $resultArray = $event->getResultArray();

        $languageService = $this->getLanguageService();
        $buttonText = htmlspecialchars(
            $languageService->sL(
                'LLL:EXT:snaatch_typo3/Resources/Private/Language/locallang_be.xlf:modal_view.button'
            )
        );

        $foreignTable = $event->getFieldConfig()['foreign_table'] ?? '';
        $objectPrefix = $event->getFormFieldIdentifier() . '-' . $foreignTable;
        $uid = uniqid('snaatch_', true);

        $iframe_url = 'https://app.vaulo.com'
            . '?appMode=file-selector'
            . '&fileSelectorAction=select'
            . '&fileSelectorAction=crop'
            . '&fileSelectorAction=multi-select'
            . '&fileSelectorMode=direct'
            . '&fileSelectorFormat=jpeg';

        $button = $this->renderSnaatchButton($buttonText, $objectPrefix, $uid, $iframe_url);

        $event->addControl($button);

        $resultArray['javaScriptModules'][] = JavaScriptModuleInstruction::create('@snaatch/typo3/ClientSideCodeV12.js');
        $resultArray['stylesheetFiles'][] = 'EXT:snaatch_typo3/Resources/Public/StyleSheet/Styles.css';
        $event->setResultArray($resultArray);
    }

    protected function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }
}
