<?php

namespace Drupal\straker_translate\FormComponent;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentArchivedException;

/**
 *
 */
class StrakerTranslateFormComponentBulkActionExecutor {

  /**
   *
   */
  public function doExecute(StrakerTranslateFormComponentBulkActionInterface $action, array $entities, array $options, StrakerTranslateFormComponentBulkActionInterface $fallbackAction = NULL) {
    try {
      $result = $action->execute($entities, $options, $this);
    }
    catch (StrakerTranslateDocumentArchivedException $archivedException) {
      if ($fallbackAction) {
        $result = $fallbackAction->execute($entities, $options, $this);
      }
      else {
        throw $archivedException;
      }
    }
    return $result;
  }

  /**
   *
   */
  public function execute(StrakerTranslateFormComponentBulkActionInterface $action, array $entities, array $options, StrakerTranslateFormComponentBulkActionInterface $fallbackAction = NULL) {
    if ($action->isBatched() && $action->hasBatchBuilder()) {
      /** @var \Drupal\straker_translate\Plugin\StrakerTranslateFormComponent\BulkAction\DownloadTranslations $action */
      return $action->createBatch($this, $entities, $options, $fallbackAction);
    }
    elseif ($action->isBatched()) {
      return $this->createBatch($action, $entities, $options, $fallbackAction);
    }
    else {
      return $action->execute($entities, $options, $this);
    }
  }

  /**
   *
   */
  public function doExecuteSingle(StrakerTranslateFormComponentBulkActionInterface $action, ContentEntityInterface $entity, array $options, StrakerTranslateFormComponentBulkActionInterface $fallbackAction = NULL, array &$context) {
    try {
      $result = $action->executeSingle($entity, $options, $this, $context);
    }
    catch (StrakerTranslateDocumentArchivedException $archivedException) {
      if ($fallbackAction) {
        $result = $fallbackAction->executeSingle($entity, $options, $this, $context);
      }
      else {
        throw $archivedException;
      }
    }
    return $result;
  }

  /**
   * Create and set a batch.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   Array of entities to process.
   * @param array $options
   *   Array of options.
   */
  protected function createBatch(StrakerTranslateFormComponentBulkActionInterface $action, $entities, array $options, StrakerTranslateFormComponentBulkActionInterface $fallbackAction = NULL) {
    $operations = [];
    foreach ($entities as $entity) {
      $operations[] = [[$this, 'doExecuteSingle'], [$action, $entity, $options, $fallbackAction]];
    }
    $batch = [
      'title' => $action->getTitle(),
      'operations' => $operations,
      'finished' => [$action, 'finished'],
      'progressive' => TRUE,
    ];
    batch_set($batch);
    return TRUE;
  }

}
