<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap_starterkit\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Extension\ThemeExtensionList;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Alter libraries not overridable with them.info.yml.
 */
class LibraryInfoAlter implements ContainerInjectionInterface {

  /**
   * The parent theme.
   */
  public const PARENT_THEME = 'sobki_theme_bootstrap';

  /**
   * The theme.
   */
  public const THEME = 'sobki_theme_bootstrap_starterkit';

  /**
   * The theme extension list.
   *
   * @var \Drupal\Core\Extension\ThemeExtensionList
   */
  protected ThemeExtensionList $themeExtensionList;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Extension\ThemeExtensionList $themeExtensionList
   *   The theme extension list.
   */
  public function __construct(
    ThemeExtensionList $themeExtensionList,
  ) {
    $this->themeExtensionList = $themeExtensionList;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('extension.list.theme')
    );
  }

  /**
   * Alter libraries definitions.
   *
   * @param array $libraries
   *   An associative array of libraries, passed by reference. The array key
   *   for any particular library will be the name registered in
   *   *.libraries.yml.
   *   In the example below, the array key would be $libraries['foo'].
   * @param string $extension
   *   Can either be 'core' or the machine name of the extension that registered
   *   the libraries.
   */
  public function alter(&$libraries, $extension): void {
    if ($extension != 'ui_patterns') {
      return;
    }

    $parent_theme_path = $this->themeExtensionList->getPath(static::PARENT_THEME);
    $theme_path = $this->themeExtensionList->getPath(static::THEME);

    if (isset($libraries['navbar.styles']['css']['component']['/' . $parent_theme_path . '/templates/patterns/navbar/styles/navbar.css'])) {
      $libraries['navbar.styles']['css']['component']['/' . $theme_path . '/templates/patterns/navbar/styles/navbar.css'] = $libraries['navbar.styles']['css']['component']['/' . $parent_theme_path . '/templates/patterns/navbar/styles/navbar.css'];
      unset($libraries['navbar.styles']['css']['component']['/' . $parent_theme_path . '/templates/patterns/navbar/styles/navbar.css']);
    }
  }

}
