<?php

namespace Drupal\pagedesigner_media\Plugin;

use Drupal\Core\Language\LanguageInterface;
use Drupal\media\Entity\Media;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\PlainFieldHandlerBase;

/**
 * Povides the media field handler base class for pagedesigner elements.
 *
 * The media handler provides methods for handling
 * media trait pagedesigner elements (e.g. audio, image etc.)
 * It is to be extended and the inherited class
 * to be annotated for the correct type of pagedesiger element.
 */
class MediaFieldHandlerBase extends PlainFieldHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $data = [
      'src' => '',
      'id' => $entity->field_media->target_id,
    ];
    $this->get($entity, $data['src']);
    $result = $data + $result;
  }

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    $medium = static::getMediaTranslation($entity->field_media->entity);
    if ($medium != NULL) {
      if ($medium->field_media_file->entity != NULL) {
        $result = $medium->field_media_file->entity->createFileUrl();
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getContent(Element $entity, array &$list = [], $published = TRUE) {

  }

  /**
   * {@inheritdoc}
   */
  public function view(Element $entity, string $view_mode, array &$build = []) {
    \Drupal::service('renderer')->addCacheableDependency($build, $entity->field_media->entity);
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    $build = [];
    parent::build($entity, $view_mode, $build);
  }

  /**
   * {@inheritdoc}
   */
  public function patch(Element $entity, array $data) {
    // Treat empty or non-numeric ids as null.
    $id = empty($data['id']) || !is_numeric($data['id']) ? NULL : $data['id'];
    $entity->field_media->target_id = $id;
    $entity->saveEdit();
  }

  /**
   * Get media translation, if available.
   *
   * Retrieves the content language translation of the given medium.
   * Returns the given medium if no translation available.
   *
   * @param \Drupal\media\Entity\Media $medium
   *   The media entity.
   *
   * @return \Drupal\media\Entity\Media
   *   The media entity translation, if available.
   */
  public static function getMediaTranslation(Media $medium = NULL) {
    if ($medium != NULL) {
      $language = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
      if ($medium->hasTranslation($language)) {
        $medium = $medium->getTranslation($language);
      }
    }
    return $medium;
  }

  /**
   * Adds infos about the media type to drupalSettings.
   *
   * @param array $attachments
   *   The attachments array.
   * @param string $type
   *   The media type.
   */
  public static function addMediaTypeInfo(array &$attachments, string $type) {
    if (empty($attachments['drupalSettings']['pagedesigner']['media'])) {
      $attachments['drupalSettings']['pagedesigner']['media'] = [];
    }
    if (\Drupal::service('pagedesigner.service')->isEditMode()) {
      $attachments['drupalSettings']['pagedesigner']['media'][$type] = ['translatable' => FALSE];

      $config = \Drupal::configFactory()->get('language.content_settings.media.' . $type);
      $thirdPartySettings = $config->get('third_party_settings');
      if ($config->get('language_alterable') && $thirdPartySettings && $thirdPartySettings['content_translation']['enabled']) {
        $attachments['drupalSettings']['pagedesigner']['media'][$type]['translatable'] = TRUE;
      }
    }
  }

}
