<?php

namespace Drupal\simple_interactive_maps;

/**
 * Helper class to encapsulate render functions.
 *
 * @package Drupal\simple_interactive_maps
 */
class MapRenderHelper {

  /**
   * The map render array.
   *
   * @var array
   */
  protected array $renderArray = [];

  /**
   * The map settings.
   *
   * @var array
   */
  protected array $settings = [];

  /**
   * MapRenderHelper constructor.
   *
   * @param array $renderArray
   *   The map render array.
   * @param array $settings
   *   The map settings.
   */
  public function __construct(array $renderArray = [], array $settings = []) {
    $this->renderArray = $renderArray;
    $this->settings = $settings;
  }

  /**
   * Get the map render array.
   *
   * @return array
   *   The map render array.
   */
  public function getRenderArray(): array {
    return $this->renderArray;
  }

  /**
   * Get the map settings.
   *
   * @return array
   *   The map settings.
   */
  public function getSettings(): array {
    return $this->settings;
  }

  /**
   * Set the map render array.
   *
   * @param array $renderArray
   *   The map render array.
   */
  public function setRenderArray(array $renderArray): void {
    $this->renderArray = $renderArray;
  }

  /**
   * Set the map settings.
   *
   * @param array $settings
   *   The map settings.
   */
  public function setSettings(array $settings): void {
    $this->settings = $settings;
  }

  /**
   * Extract the unique action libraries that need to be included for this map.
   *
   * @param \Drupal\simple_interactive_maps\MapActionPluginManager $actionPluginManager
   *   The map action plugin manager.
   *
   * @return array
   *   List of libraries to include.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function getActionLibraries(MapActionPluginManager $actionPluginManager): array {
    $libraries = [];

    foreach ($this->settings as $setting) {
      if (!array_key_exists($setting['action']['name'], $libraries)) {
        /** @var \Drupal\simple_interactive_maps\MapActionInterface $plugin */
        $plugin = $actionPluginManager->createInstance($setting['action']['name'], $setting['action']['configuration']);
        $libraries[$setting['action']['name']] = $plugin->getActionLibrary();
      }
    }

    return $libraries;
  }

}
