<?php

declare(strict_types=1);

namespace Drupal\sobki_assets\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\sobki_assets\Form\AssetsUploadForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Alter libraries.
 */
class LibraryInfoAlter implements ContainerInjectionInterface {

  public function __construct(
    protected FileUrlGeneratorInterface $fileUrlGenerator,
    protected FileSystemInterface $fileSystem,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('file_url_generator'),
      $container->get('file_system'),
    );
  }

  /**
   * Add uploaded CSS files to ui_suite_bootstrap/bootstrap library.
   *
   * @param array $libraries
   *   An associative array of libraries, passed by reference.
   * @param string $extension
   *   Can either be 'core' or the machine name of the extension that registered
   *   the libraries.
   */
  public function alter(array &$libraries, string $extension): void {
    if ($extension != 'ui_suite_bootstrap') {
      return;
    }

    if (!isset($libraries['bootstrap'])) {
      return;
    }

    $destination = $this->fileUrlGenerator->generateString(AssetsUploadForm::DESTINATION_DIRECTORY);
    /** @var object{"filename": string}[] $files */
    $files = $this->fileSystem->scanDirectory(AssetsUploadForm::DESTINATION_DIRECTORY, '/\.css/');
    foreach ($files as $file) {
      $libraries['bootstrap']['css']['theme'][$destination . '/' . $file->filename] = [
        'minified' => TRUE,
      ];
    }
  }

}
