<?php

namespace Drupal\pagedesigner_multitheme\EventSubscriber;

use Drupal\Core\Theme\ThemeManager;
use Drupal\pagedesigner\ElementEvents;
use Drupal\pagedesigner\Event\ElementEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber to filter patterns according to theme.
 */
class FilterSubscriber implements EventSubscriberInterface {

  /**
   * Active theme and its parents.
   *
   * @var \Drupal\Core\Extension\Extension[]
   */
  protected $themes = [];

  /**
   * Create the FilterSubscriber.
   *
   *   The theme manager.
   */
  public function __construct(ThemeManager $themeManager) {
    $activeTheme = $themeManager->getActiveTheme();
    $this->themes = array_keys($activeTheme->getBaseThemeExtensions());
    $this->themes[] = $activeTheme->getName();
  }

  /**
   * Filter patterns for current theme.
   *
   *   The event with the patterns data.
   */
  public function filterPatterns(ElementEvent $event) {
    $data = &$event->getData();
    $filteredDefinitions = [];
    foreach ($data[0] as $id => $definition) {
      if ($definition->getProvider() == NULL || in_array($definition->getProvider(), $this->themes)) {
        $filteredDefinitions[$id] = $definition;
      }
    }
    $data[0] = $filteredDefinitions;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      ElementEvents::COLLECTPATTERNS_AFTER => ['filterPatterns', 100],
    ];
  }

}
