<?php

declare(strict_types=1);

namespace Drupal\lms_xapi\Plugin\Field\FieldFormatter;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\lms_xapi\Plugin\Field\FieldType\XapiItem;
use Drupal\lms_xapi\XapiService;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'lms_xapi' formatter.
 */
#[FieldFormatter(
  id: 'lms_xapi',
  label: new TranslatableMarkup('Embedded Xapi content'),
  description: new TranslatableMarkup('Iframe'),
  field_types: ['lms_xapi'],
)]
final class XapiFieldFormatter extends FormatterBase {

  /**
   * Constructor.
   */
  public function __construct(
    $plugin_id,
    $plugin_definition,
    FieldDefinitionInterface $field_definition,
    array $settings,
    $label,
    $view_mode,
    array $third_party_settings,
    protected readonly AccountInterface $currentUser,
    protected readonly XapiService $xapi,
  ) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'],
      $container->get(AccountInterface::class),
      $container->get(XapiService::class),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {

    // Don't cache in case of invalid / missing data.
    $no_cache_return = [
      '#cache' => [
        'max-age' => 0,
      ],
    ];

    $item = $items->first();
    if (!$item instanceof XapiItem) {
      return [0 => $no_cache_return];
    }

    $cacheable_metadata = new CacheableMetadata();

    $launch_url = $this->xapi->getLaunchUrl(
      $item->getPackagePath(),
      $item->getEntity(),
      $this->currentUser,
      $cacheable_metadata
    );
    if ($launch_url === NULL) {
      return [0 => $no_cache_return];
    }

    $build = [
      '#type' => 'html_tag',
      '#tag' => 'iframe',
      '#attributes' => [
        'id' => 'xapi-iframe',
        'src' => $launch_url,
        'style' => 'width: 100%; min-height: 800px; border: 0;',
      ],
      '#value' => '',
    ];
    $cacheable_metadata->applyTo($build);
    return [0 => $build];
  }

}
