<?php

declare(strict_types=1);

namespace Drupal\openculturas_teaser\Plugin\paragraphs\Behavior;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Template\Attribute;
use Drupal\paragraphs\Attribute\ParagraphsBehavior;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\ParagraphsTypeInterface;
use Drupal\taxonomy\TermInterface;
use function sprintf;

#[ParagraphsBehavior(
  id: 'term_teaser',
  label: new TranslatableMarkup('Term teaser.'),
  description: new TranslatableMarkup("Allow overriding term's teaser values."),
  weight: 2
)]
class TermTeaserBehavior extends TeaserBehaviorBase {

  /**
   * {@inheritdoc}
   */
  protected string $descriptionField = 'description';

  /**
   * {@inheritdoc}
   */
  public function buildBehaviorForm(ParagraphInterface $paragraph, array &$form, FormStateInterface $form_state): array {
    parent::buildBehaviorForm($paragraph, $form, $form_state);
    $referenceItems = $paragraph->get('field_term')->referencedEntities();
    $entity = reset($referenceItems);
    if ($entity instanceof TermInterface && !$entity->hasField('field_subtitle')) {
      unset($form['subtitle']);
    }

    // Hint: Do not return the form, or we get the ugly paragraphs-behavior tabs, which we do not want. See internal issue 863.
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function view(array &$build, ParagraphInterface $paragraph, EntityViewDisplayInterface $display, $view_mode): void {
    $settings = $paragraph->getAllBehaviorSettings()[$this->getPluginId()] ?? [];
    $buildTerm = &$build['field_term'][0];
    /** @var \Drupal\taxonomy\Entity\Term|NULL $term */
    $term = &$buildTerm['#taxonomy_term'];
    if ($term instanceof TermInterface) {
      $id = sprintf('%s-%s-%s', $paragraph->bundle(), $paragraph->id(), $term->id());
      $buildTerm = $this->getBaseBuildArray($buildTerm, $settings, '#taxonomy_term');
      $buildTerm['#attributes'] = new Attribute([
        'class' => [
          'teaser-internal',
          'teaser-term',
        ],
        'id' => $id,
      ]);
      $cacheableMetadata = CacheableMetadata::createFromRenderArray($buildTerm);
      $cacheableMetadata->addCacheableDependency($paragraph);
      $cacheableMetadata->applyTo($buildTerm);
      // We need an additional cache key, or the field renders all references
      // with default cache keys. (entity_view:ENTITY_TYPE_ID:ENTITY_ID:VIEW_MODE).
      $buildTerm['#cache']['keys'][] = 'ParagraphsBehavior-' . $paragraph->id();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(ParagraphsTypeInterface $paragraphs_type): bool {
    $fieldManager = \Drupal::service('entity_field.manager');
    $fd = $fieldManager->getFieldDefinitions('paragraph', (string) $paragraphs_type->id());
    $ef = $fieldManager->getBaseFieldDefinitions('paragraph');
    $fieldKeys = array_diff(array_keys($fd), array_keys($ef));
    foreach ($fieldKeys as $item) {
      $fieldDefinition = $fd[$item];
      if ($fieldDefinition->getType() === 'entity_reference') {
        $handler = $fieldDefinition->getSetting('handler');
        if ($handler === 'default:taxonomy_term') {
          return TRUE;
        }
      }
    }

    return FALSE;
  }

}
