<?php

namespace Drupal\pagedesigner\Plugin\rest\resource;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\pagedesigner\Service\ElementHandler;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\ui_patterns\Definition\PatternDefinition;
use Drupal\ui_patterns\UiPatternsManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "pagedesigner_pattern",
 *   label = @Translation("Pagedesigner patterns"),
 *   uri_paths = {
 *     "canonical" = "/pagedesigner/pattern"
 *   }
 * )
 */
class PatternResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The pattern manager.
   *
   * @var \Drupal\ui_patterns\UiPatternsManager
   */
  protected $patternManager;

  /**
   * The element handler.
   *
   * @var Drupal\pagedesigner\Service\ElementHandler
   */
  protected $elementHandler;

  /**
   * Constructs a new PatternResource object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   * @param \Drupal\ui_patterns\UiPatternsManager $pattern_manager
   *   The pattern manager.
   * @param \Drupal\pagedesigner\Service\ElementHandler $element_handler
   *   The pagedesigner element handler.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user,
    UiPatternsManager $pattern_manager,
    ElementHandler $element_handler,
  ) {

    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
    $this->patternManager = $pattern_manager;
    $this->elementHandler = $element_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
          $configuration,
          $plugin_id,
          $plugin_definition,
          $container->getParameter('serializer.formats'),
          $container->get('logger.factory')->get('pagedesigner'),
          $container->get('current_user'),
          $container->get('plugin.manager.ui_patterns'),
          $container->get('pagedesigner.service.element_handler')
      );
  }

  /**
   * Responds to GET requests.
   *
   *   The entity object.
   *
   * @return \Drupal\rest\ResourceResponse
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get(EntityInterface $entity = NULL) {
    $patterns = [];
    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if ($this->currentUser->hasPermission('edit pagedesigner element entities')) {
      if ($entity == NULL) {
        $type = 'element';
        $designerPermission = $this->currentUser->hasPermission('access pagedesigner designer patterns');
        $stylingPermission = $this->currentUser->hasPermission('edit pagedesigner styles');

        $patternDefinitions = $this->patternManager->getDefinitions();
        $this->elementHandler->collectPatterns($patternDefinitions, TRUE);
        foreach ($patternDefinitions as $id => $definition) {
          $additional = $definition->getAdditional();

          if (!isset($additional['type'])) {
            continue;
          }
          // Check if the pattern is meant for the page designer.
          if (empty($additional['pagedesigner']) || $additional['pagedesigner'] == 0) {
            continue;
          }

          // Check if the pattern is for designer only.
          if (!empty($additional['designer']) && !$designerPermission) {
            continue;
          }

          $category = $definition->getCategory() ?: 'Other';
          $category = $this->t($category, [], ['context' => 'pd_pattern']);
          $additional['category'] = $category;

          $icon = (!empty($additional['icon'])) ? $additional['icon'] : 'fas fa-square';
          $type = (!empty($additional['type'])) ? $additional['type'] : 'standard';

          $styles = [];
          if ($stylingPermission) {
            $styles = (!empty($additional['styles'])) ? $additional['styles'] : $styles;
          }

          $weight = $definition->getWeight() ?: 1000;
          $markup = (!empty($additional['markup'])) ? $additional['markup'] : '';

          $label = $definition->getLabel();
          if (\is_string($label)) {
            $label = $this->t($label, [], ['context' => 'pd_pattern']);
          }
          $description = $definition->getDescription();
          if (!empty($description)) {
            $description = $this->t($description, [], ['context' => 'pd_pattern']);
          }
          $filename = $definition->getBasePath() . '/' . $definition->getTemplate() . '.html.twig';
          if (empty($markup) && \file_exists($filename)) {
            $markup = \file_get_contents($filename);
          }
          if (empty($markup)) {
            continue;
          }

          if (!empty($additional['classes'])) {
            foreach ($additional['classes'] as $key => $class) {
              $additional['classes'][$key]['label'] = $this->t($class['label'], [], ['context' => 'pd_pattern']);
              $additional['classes'][$key]['description'] = $this->t($class['description'], [], ['context' => 'pd_pattern']);
            }
          }

          if (!empty($additional['styling_options'])) {
            foreach ($additional['styling_options'] as $key => $option) {
              $additional['styling_options'][$key]['label'] = $this->t($option['label'], [], ['context' => 'pd_pattern']);
              foreach ($option['options'] as $optionKey => $optionItem) {
                $additional['styling_options'][$key]['options'][$optionKey] = $this->t($optionItem, [], ['context' => 'pd_pattern']);
              }
            }
          }

          $definitionArray = [
            'label' => $label,
            'description' => $description,
            'fields' => $this->getFields($definition),
            'icon' => $icon,
            'category' => $category,
            'markup' => $markup,
            'type' => $type,
            'additional' => $additional,
            'styles' => $styles,
            'weight' => $weight,
          ];
          $patterns[$id] = $definitionArray;
        }
      }

      $this->elementHandler->adaptPatterns($patterns);

      uasort(
            $patterns,
            fn(array $a, array $b) => $a['weight'] - $b['weight']
        );
    }
    $response = new ResourceResponse($patterns, 200);
    $response->addCacheableDependency(['cache' => ['max-age' => 0]]);
    return $response;
  }

  /**
   * Get fields of pattern by definition.
   *
   *   The pattern defitiontion.
   */
  protected function getFields(PatternDefinition $definition) {
    $fields = [];
    foreach ($definition->getFields() as $id => $field) {
      $label = $field->getLabel();
      if (\is_string($label)) {
        $label = $this->t($label, [], ['context' => 'pd_pattern']);
      }
      $description = $field->getDescription();
      if (!empty($description)) {
        $description = $this->t($description, [], ['context' => 'pd_pattern']);
      }

      $fields[$id] = [
        'description' => $description,
        'label' => $label,
        'name' => $field->getName(),
        'preview' => $field->getPreview(),
        'type' => $field->getType(),
        'additional' => $field->getAdditional(),
      ];
      $this->elementHandler->prepare($field, $fields[$id]);
    }
    return $fields;
  }

}
