<?php

/**
 * @file
 * Contains farm_log.module.
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_entity_prepare_form().
 */
function farm_log_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {

  // If not adding a new entity, bail.
  if ($operation !== 'add' || !$entity->isNew()) {
    return;
  }

  // If the entity is not a log, bail.
  if ($entity->getEntityTypeId() !== 'log') {
    return;
  }

  // Save the current user.
  $user = \Drupal::currentUser();

  // Save the request query params.
  $query = \Drupal::request()->query;

  // Prepopulate the log asset field.
  $asset_ids = $query->get('asset');
  if (!empty($asset_ids)) {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemList $asset_field */
    $asset_field = $entity->get('asset');

    // Wrap in an array, if necessary.
    if (!is_array($asset_ids)) {
      $asset_ids = [$asset_ids];
    }

    // Add each asset the user has view access to.
    $assets = \Drupal::entityTypeManager()->getStorage('asset')->loadMultiple($asset_ids);
    foreach ($assets as $asset) {
      if ($asset->access('view', $user)) {
        $asset_field->appendItem($asset);
      }
    }

    $entity->set('asset', $asset_ids);
  }

}

/**
 * Generate a summary of asset names for use in a log name.
 *
 * Note that this function does NOT sanitize the asset names. This is the
 * responsibility of downstream code, if it is printing the text to the page.
 *
 * @param \Drupal\asset\Entity\AssetInterface[] $assets
 *   An array of assets.
 * @param int $cutoff
 *   The number of asset names to include before summarizing the rest.
 *   If the number of assets exceeds the cutoff, the rest will be summarized
 *   as "(+X more)". If the number of assets is less than or equal to the
 *   cutoff, or if the cutoff is 0, all asset names will be included.
 *
 * @return string
 *   Returns a string summarizing the assets.
 */
function farm_log_asset_names_summary(array $assets, $cutoff = 3) {
  /** @var \Drupal\asset\Entity\AssetInterface[] $assets */
  $names = [];
  foreach ($assets as $asset) {
    $names[] = $asset->label();
  }
  if ($cutoff != 0) {
    array_splice($names, $cutoff);
  }
  $output = implode(', ', $names);
  $diff = count($assets) - count($names);
  if ($diff > 0) {
    $output .= ' (+' . $diff . ' ' . t('more') . ')';
  }
  return $output;
}
