<?php

namespace Drupal\entity_usage;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Utility\Error;

/**
 * Manages Entity Usage integration with Batch API specifically for the queue.
 *
 * This is different than EntityUsageBatchManager in that here we want to have
 * statistics regenerated in background through a standard Drupal queue, but in
 * order to create items for the queue, we will use a batch process, to avoid
 * timeouts and memory issues.
 */
class EntityUsageQueueBatchManager {

  use StringTranslationTrait;

  /**
   * The default size of the batch for the revision queries.
   */
  const BATCH_SIZE = 100;

  /**
   * Creates a EntityUsageQueueBatchManager object.
   */
  final public function __construct(
    private EntityTypeManagerInterface $entityTypeManager,
    TranslationInterface $stringTranslation,
    private ConfigFactoryInterface $configFactory,
  ) {
    $this->setStringTranslation($stringTranslation);
  }

  /**
   * Populate the queue to recreate the entity usage statistics.
   *
   * Generate a batch to queue and recreate the statistics for all entities.
   *
   * @param int $batch_size
   *   (Optional) The batch size to use when executing the batch process to
   *   populate the queue. Defaults to static::BATCH_SIZE.
   * @param bool $keep_existing_records
   *   (Optional) If TRUE existing usage records won't be deleted. Defaults to
   *   FALSE.
   */
  public function populateQueue($batch_size = 0, $keep_existing_records = FALSE) {
    $batch = $this->generateBatch($batch_size, $keep_existing_records);
    batch_set($batch);
  }

  /**
   * Create a batch to queue the entity types in bulk.
   *
   * @param int $batch_size
   *   (Optional) The batch size to use when executing the batch process to
   *   populate the queue. Defaults to static::BATCH_SIZE.
   * @param bool $keep_existing_records
   *   (Optional) If TRUE existing usage records won't be deleted. Defaults to
   *   FALSE.
   *
   * @return array{operations: array<array{callable-string, array}>, finished: callable-string, title: \Drupal\Core\StringTranslation\TranslatableMarkup, progress_message: \Drupal\Core\StringTranslation\TranslatableMarkup, error_message: \Drupal\Core\StringTranslation\TranslatableMarkup}
   *   The batch array.
   */
  public function generateBatch($batch_size = 0, $keep_existing_records = FALSE) {
    $batch_size = (int) $batch_size > 0 ? (int) $batch_size : static::BATCH_SIZE;
    $operations = [];
    $to_track = $this->configFactory
      ->get('entity_usage.settings')
      ->get('track_enabled_source_entity_types');
    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      // Only look for entities enabled for tracking on the settings form.
      $track_this_entity_type = FALSE;
      if (!is_array($to_track) && ($entity_type->entityClassImplements('\Drupal\Core\Entity\ContentEntityInterface'))) {
        // When no settings are defined, track all content entities by default,
        // except for Files and Users.
        if (!in_array($entity_type_id, ['file', 'user'])) {
          $track_this_entity_type = TRUE;
        }
      }
      elseif (is_array($to_track) && in_array($entity_type_id, $to_track, TRUE)) {
        $track_this_entity_type = TRUE;
      }
      if ($track_this_entity_type) {
        $operations[] = [
          '\Drupal\entity_usage\EntityUsageQueueBatchManager::queueSourcesBatchWorker',
          [$entity_type_id, $batch_size, $keep_existing_records],
        ];
      }
    }

    $batch = [
      'operations' => $operations,
      'finished' => '\Drupal\entity_usage\EntityUsageQueueBatchManager::batchFinished',
      'title' => $this->t('Populating queue to recreate entity usage statistics.'),
      'progress_message' => $this->t('Queued @current of @total entity types.'),
      'error_message' => $this->t('This batch encountered an error.'),
    ];

    return $batch;
  }

  /**
   * Batch operation worker for populating the queue to regenerate statistics.
   *
   * @param string $entity_type_id
   *   The entity type id, for example 'node'.
   * @param int $batch_size
   *   The batch size.
   * @param bool $keep_existing_records
   *   If TRUE existing usage records won't be deleted.
   * @param array{sandbox: array{progress?: int, total?: int, current_item?: int}, results: string[], finished: int, message: string} $context
   *   Batch context. May be an array, or implementing \ArrayObject in the case
   *   of Drush.
   */
  public static function queueSourcesBatchWorker($entity_type_id, $batch_size, $keep_existing_records, &$context) {
    $queue = \Drupal::queue('entity_usage_regenerate_queue');

    $entity_storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
    $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
    $entity_type_key = $entity_type->getKey('id');

    // First pass, populate the sandbox.
    if (empty($context['sandbox']['total'])) {
      // Delete current usage statistics for these entities.
      if (!$keep_existing_records) {
        \Drupal::service('entity_usage.usage')
          ->bulkDeleteSources($entity_type_id);
      }

      $context['sandbox']['progress'] = 0;
      if ($entity_type->isRevisionable()) {
        // Set the total to the number of revisions.
        $context['sandbox']['total'] = (int) $entity_storage->getQuery()
          ->allRevisions()
          ->accessCheck(FALSE)
          ->count()
          ->execute();
      }
      else {
        // Set the total to the number of entities.
        $context['sandbox']['total'] = (int) $entity_storage->getQuery()
          ->accessCheck(FALSE)
          ->count()
          ->execute();
      }
      $context['sandbox']['current_item'] = 0;
      $context['finished'] = 0;
    }

    if ($context['sandbox']['total'] > 0) {
      try {
        if ($entity_type->isRevisionable()) {
          $entity_type_revision_key = $entity_type->getKey('revision');
          $current_vid = $context['sandbox']['current_item'];
          // Query entity revisions in batches.
          $result = $entity_storage->getQuery()->allRevisions()
            ->condition($entity_type_revision_key, $current_vid, '>')
            ->accessCheck(FALSE)
            ->sort($entity_type_revision_key)
            ->range(0, $batch_size)
            ->execute();
          $revision_ids = array_keys($result);
          foreach ($revision_ids as $revision_id) {
            // Add the queue record.
            $queue->createItem([
              'entity_type' => $entity_type_id,
              'entity_revision_id' => $revision_id,
            ]);
            $context['sandbox']['current_item'] = $revision_id;
            $context['sandbox']['progress']++;
          }
        }
        else {
          // Query entities in batches.
          $current_id = $context['sandbox']['current_item'];
          $result = $entity_storage->getQuery()
            ->condition($entity_type_key, $current_id, '>')
            ->accessCheck(FALSE)
            ->sort($entity_type_key)
            ->range(0, $batch_size)
            ->execute();
          $entity_ids = array_keys($result);
          foreach ($entity_ids as $entity_id) {
            $queue->createItem([
              'entity_type' => $entity_type_id,
              'entity_id' => $entity_id,
            ]);
            $context['sandbox']['current_item'] = $entity_id;
            $context['sandbox']['progress']++;
          }
        }
      }
      catch (\Exception $e) {
        Error::logException(\Drupal::logger('entity_usage.batch'), $e);
      }

      $context['results'][] = $entity_type_id;
    }

    if ($context['sandbox']['progress'] < $context['sandbox']['total']) {
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['total'];
    }
    else {
      $context['finished'] = 1;
    }

    $context['message'] = t('Populating entity usage queue for entity type @entity_type: @current of @total', [
      '@entity_type' => $entity_type_id,
      '@current' => $context['sandbox']['progress'],
      '@total' => $context['sandbox']['total'],
    ]);
  }

  /**
   * Finish callback for our batch processing.
   *
   * @param bool $success
   *   Whether the batch completed successfully.
   * @param array $results
   *   The results array.
   * @param array $operations
   *   The operations array.
   */
  public static function batchFinished($success, array $results, array $operations) {
    if ($success) {
      $types = array_unique($results);
      \Drupal::messenger()->addStatus(t('Created queue items to regenerate entity usage statistics for entity types: @types.', [
        '@types' => implode(", ", $types),
      ]));
      \Drupal::messenger()->addStatus(t('Important! Statistics will not be accurate until all queue items have been processed. Use "drush queue:list" to check the current number of unprocessed items in the queue "entity_usage_regenerate_queue".'));
    }
    else {
      // An error occurred.
      // $operations contains the operations that remained unprocessed.
      $error_operation = reset($operations);
      \Drupal::messenger()->addMessage(
        t('An error occurred while processing @operation with arguments : @args',
          [
            '@operation' => $error_operation[0],
            '@args' => print_r($error_operation[0], TRUE),
          ]
        )
      );
    }
  }

}
