<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFieldProcessor;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\straker_translate\FieldProcessor\StrakerTranslateFieldProcessorInterface;
use Drupal\straker_translate\StrakerTranslateConfigTranslationServiceInterface;
use Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface;
use Drupal\straker_translate\StrakerTranslateContentTranslationEntityRevisionResolver;
use Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @StrakerTranslateFieldProcessor(
 *   id = "block_field",
 *   weight = 5,
 * )
 */
class StrakerTranslateBlockFieldProcessor extends PluginBase implements StrakerTranslateFieldProcessorInterface, ContainerFactoryPluginInterface {

  /**
   * The Straker Translate configuration service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface
   */
  protected $straker_translateConfiguration;

  /**
   * The Straker Translate configuration translation service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateConfigTranslationServiceInterface
   */
  protected $straker_translateConfigTranslation;

  /**
   * The Straker Translate content translation service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface
   */
  protected $straker_translateContentTranslation;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity repository.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * The typed config handler.
   *
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfig;

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs a new UploadToStrakerTranslateAction action.
   *
   * @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 \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $repository
   *   The entity repository.
   * @param \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface $straker_translate_configuration
   *   The Straker Translate configuration service.
   * @param \Drupal\straker_translate\StrakerTranslateConfigTranslationServiceInterface $straker_translate_config_translation
   *   The Straker Translate config translation service.
   * @param \Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface $straker_translate_content_translation
   *   The Straker Translate content translation service.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
   *   The typed config handler.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $repository, StrakerTranslateConfigurationServiceInterface $straker_translate_configuration, StrakerTranslateConfigTranslationServiceInterface $straker_translate_config_translation, StrakerTranslateContentTranslationServiceInterface $straker_translate_content_translation, TypedConfigManagerInterface $typed_config, LoggerInterface $logger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityRepository = $repository;
    $this->straker_translateConfiguration = $straker_translate_configuration;
    $this->straker_translateConfigTranslation = $straker_translate_config_translation;
    $this->straker_translateContentTranslation = $straker_translate_content_translation;
    $this->typedConfig = $typed_config;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('entity.repository'),
      $container->get('straker_translate.configuration'),
      $container->get('straker_translate.config_translation'),
      $container->get('straker_translate.content_translation'),
      $container->get('config.typed'),
      $container->get('logger.factory')->get('straker_translate')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function appliesToField(FieldDefinitionInterface $field_definition, ContentEntityInterface &$entity) {
    return 'block_field' === $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) {
    /** @var \Drupal\block_field\Plugin\Field\FieldType\BlockFieldItem  $field_item */
    foreach ($entity->get($field_name) as $delta => $field_item) {
      $pluginId = $field_item->get('plugin_id')->getValue();
      $block_instance = $field_item->getBlock();
      $pluginIDName = $block_instance->getPluginDefinition()['id'];
      $blockConfig = $block_instance->getConfiguration();
      $definition = $this->typedConfig->getDefinition('block.settings.' . $pluginIDName);
      if ($definition['type'] == 'undefined') {
        $definition = $this->typedConfig->getDefinition('block_settings');
      }
      $dataDefinition = $this->typedConfig->buildDataDefinition($definition, $blockConfig);
      $schema = $this->typedConfig->create($dataDefinition, $blockConfig);
      $properties = $this->straker_translateConfigTranslation->getTranslatableProperties($schema, NULL);
      $embedded_data = [];
      foreach ($properties as $property) {
        $propertyParts = explode('.', $property);
        $embedded_data[$property] = NestedArray::getValue($blockConfig, $propertyParts);
      }
      if (strpos($pluginId, 'block_content') === 0) {
        $uuid = $block_instance->getDerivativeId();
        if ($block = $this->entityRepository->loadEntityByUuid('block_content', $uuid)) {
          $embedded_data['entity'] = $this->straker_translateContentTranslation->getSourceData($block, $visited, $revision_mode);
        }
      }
      $data[$field_name][$delta] = $embedded_data;
    }
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function store(ContentEntityInterface &$translation, string $langcode, ContentEntityInterface &$revision, string $field_name, FieldDefinitionInterface $field_definition, array &$field_data) {
    $translation->set($field_name, NULL);
    /** @var \Drupal\block_field\Plugin\Field\FieldType\BlockFieldItem  $field_item */
    foreach ($field_data as $delta => $field_item) {
      /** @var \Drupal\block_field\Plugin\Field\FieldType\BlockFieldItem  $blockObj */
      $blockObj = $revision->get($field_name)->get($delta);
      /** @var \Drupal\Core\Block\BlockPluginInterface $block */
      $block = $blockObj->getBlock();
      if ($block !== NULL) {
        $entityData = NULL;
        if (isset($field_item['entity'])) {
          $entityData = $field_item['entity'];
          unset($field_item['entity']);
        }
        $configuration = $block->getConfiguration();
        $newConfiguration = $configuration;
        foreach ($field_item as $fieldItemProperty => $fieldItemPropertyData) {
          $componentDataKeyParts = explode('.', $fieldItemProperty);
          NestedArray::setValue($newConfiguration, $componentDataKeyParts, $fieldItemPropertyData);
        }
        $translation->get($field_name)->set($delta, [
          'plugin_id' => $block->getPluginId(),
          'settings' => $newConfiguration,
        ]);
        if ($entityData !== NULL) {
          $embedded_entity_id = NULL;
          if (isset($entityData['_straker_translate_metadata'])) {
            $target_entity_type_id = $entityData['_straker_translate_metadata']['_entity_type_id'];
            $embedded_entity_id = $entityData['_straker_translate_metadata']['_entity_id'];
            $embedded_entity_revision_id = $entityData['_straker_translate_metadata']['_entity_revision'];
            $embedded_entity = $this->entityTypeManager->getStorage($target_entity_type_id)
              ->load($embedded_entity_id);
            // We may have orphan references, so ensure that they exist before
            // continuing.
            if ($embedded_entity !== NULL) {
              if ($embedded_entity instanceof ContentEntityInterface) {
                if ($this->straker_translateConfiguration->isEnabled($embedded_entity->getEntityTypeId(), $embedded_entity->bundle())) {
                  $this->straker_translateContentTranslation->saveTargetData($embedded_entity, $langcode, $entityData);
                }
                else {
                  $this->logger
                    ->warning('Field %field not saved as its referenced entity is not translatable by Straker Translate', ['%field' => $field_name]);
                }
              }
            }
          }
        }
      }
    }
  }

}
