<?php

namespace Drupal\pagedesigner;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\ui_patterns\UiPatternsManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class to generate dynamic permissions of pagedesigner.
 */
class PagedesignerPatternPermissions implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * Ui patterns manager.
   *
   * @var \Drupal\ui_patterns\UiPatternsManager
   */
  protected $uiPatternsManager = NULL;

  /**
   * Create a new instance.
   *
   *   The ui patterns manager.
   */
  protected function __construct(UiPatternsManager $ui_patterns_manager) {
    $this->uiPatternsManager = $ui_patterns_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('plugin.manager.ui_patterns')
    );
  }

  /**
   * Get permissions for pagedesigner patterns.
   *
   * @return array
   *   Permissions array.
   */
  public function permissions() {
    $permissions = [];

    $patterns = $this->uiPatternsManager->getDefinitions();

    ksort($patterns);
    foreach ($patterns as $pattern_id => $pattern) {
      $permissions += [
        'use pattern ' . $pattern_id => [
          'title' => $this->t('Use pattern %pattern in Pagedesigner', ['%pattern' => $this->t($pattern->getLabel())]),
        ],
      ];

    }
    return $permissions;
  }

}
