<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFieldProcessor;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\straker_translate\FieldProcessor\StrakerTranslateFieldProcessorInterface;
use Drupal\straker_translate\StrakerTranslateContentTranslationEntityRevisionResolver;

/**
 * @StrakerTranslateFieldProcessor(
 *   id = "metatag",
 *   weight = 5,
 * )
 */
class StrakerTranslateMetatagProcessor extends PluginBase implements StrakerTranslateFieldProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function appliesToField(FieldDefinitionInterface $field_definition, ContentEntityInterface &$entity) {
    return 'metatag' === $field_definition->getType();
  }

  /**
   * {@inheritdoc}
   */
  public function extract(ContentEntityInterface &$entity, string $field_name, FieldDefinitionInterface $field_definition, array &$data, array &$visited = [], string $revision_mode = StrakerTranslateContentTranslationEntityRevisionResolver::RESOLVE_LATEST_TRANSLATION_AFFECTED) {
    $y = $entity->get($field_name);
    foreach ($y as $delta => $field_item) {
      $raw_data = $field_item->get('value')->getValue();
      if (!empty($raw_data)) {
        $metatags = is_array(json_decode($raw_data, TRUE)) ? json_decode($raw_data) : unserialize($raw_data);
      }
      if ($metatags) {
        $data[$field_name][$delta] = $metatags;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function store(ContentEntityInterface &$translation, string $langcode, ContentEntityInterface &$revision, string $field_name, FieldDefinitionInterface $field_definition, array &$field_data) {
    foreach ($field_data as $delta => $field_item) {
      $metatag_value = serialize($field_item);
      $translation->get($field_name)->set($delta, $metatag_value);
    }
  }

}
