<?php

namespace Drupal\author_field;

use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\field\FieldConfigInterface;

/**
 * An author field module uninstall validator.
 *
 * Finds dependency modules that have this field.
 * If there are any modules,
 * the "remove" button is added into the uninstall summaries.
 */
class AuthorFieldUninstallValidator implements ModuleUninstallValidatorInterface {
  /**
   * The entity type manager service.
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The entity field manager service.
   */
  protected EntityFieldManagerInterface $entityFieldManager;

  /**
   * Constructs a new GroupAuthorFieldUninstallValidator.
   *
   * The entity type manager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager,
        EntityFieldManagerInterface $entity_field_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * Checks the module dependencies for the content types and storage types.
   *
   * @param string $module
   *   The module.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function validate($module): array {
    $reasons = [];
    if ($module == 'author_field') {
      // $entity_type_ids = ['node' => 'node_type',
      // 'storage' => 'storage_type'];
      $entity_type_ids = ['node' => 'node_type'];
      $items_to_delete = [];

      foreach ($entity_type_ids as $field_type_id => $entity_type_id) {
        $contentTypes = $this->entityTypeManager->getStorage($entity_type_id)
          ->loadMultiple();
        foreach ($contentTypes as $contentType) {
          $type = $contentType->id();
          $fields = array_filter(
                $this->entityFieldManager->getFieldDefinitions($field_type_id, $type),
                function ($fieldDefinition) {
                    return $fieldDefinition instanceof FieldConfigInterface;
                }
            );

          foreach ($fields as $key => $definition) {
            if ($definition->getType() == 'author_field') {
              $items_to_delete[$type] = $key;
            }
          }
        }
      }
      if (!empty($items_to_delete)) {
        $reasons[] = t("<a href='/admin/modules/uninstall/entity/author_field'>Remove fields in order to uninstall this module</a> Note: Runs cron job for deletion");
      }
    }

    return $reasons;
  }

}
