<?php

/**
 * @file
 * Contains farm_log_quantity.module.
 */

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

/**
 * Implements hook_entity_base_field_info().
 */
function farm_log_quantity_entity_base_field_info(EntityTypeInterface $entity_type) {

  // We only care about log entities.
  if ($entity_type->id() != 'log') {
    return [];
  }

  // Add a quantity reference field to logs.
  $field_info = [
    'quantity' => [
      'type' => 'entity_reference_revisions',
      'label' => t('Quantity'),
      'description' => t('Add quantity measurements to this log.'),
      'target_type' => 'quantity',
      'multiple' => TRUE,
      'weight' => [
        'form' => 0,
        'view' => 0,
      ],
    ],
  ];
  $fields = [];
  foreach ($field_info as $name => $info) {
    $fields[$name] = \Drupal::service('farm_field.factory')->baseFieldDefinition($info);
  }
  return $fields;
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function farm_log_quantity_form_log_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Alter the Quantity inline entity form to set the default quantity type.
  if (!empty($form['quantity']['widget']['actions']['bundle']['#options'])) {
    $bundle_select = &$form['quantity']['widget']['actions']['bundle'];

    // Load the log type storage.
    /** @var \Drupal\log\Entity\Log $entity */
    $entity = $form_state->getFormObject()->getEntity();

    // Determine the default quantity type.
    $default_type = farm_log_quantity_default_type($entity->bundle());

    // Set the default value.
    if (array_key_exists($default_type, $bundle_select['#options'])) {
      $bundle_select['#default_value'] = $default_type;
    }
  }
}

/**
 * Returns the default quantity type.
 *
 * @param string|null $log_type
 *   The log type (optional).
 *
 * @return string|null
 *   The log's default quantity type, or NULL if a default is unavailable.
 */
function farm_log_quantity_default_type(?string $log_type = NULL) {

  // If a log type is specified, attempt to look up the default quantity type
  // from the log type's third party settings.
  if (!empty($log_type)) {
    /** @var \Drupal\log\Entity\LogType $log_type_storage */
    $log_type_definition = \Drupal::service('entity_type.manager')->getStorage('log_type')->load($log_type);
    $type = $log_type_definition->getThirdPartySetting('farm_log_quantity', 'default_quantity_type', NULL);
    if (!empty($type)) {
      return $type;
    }
  }

  // If the farm_quantity_standard module is installed, default to "standard".
  if (\Drupal::moduleHandler()->moduleExists('farm_quantity_standard')) {
    return 'standard';
  }

  // Look up all quantity types and take the first one.
  /** @var \Drupal\quantity\Entity\QuantityInterface[] $quantity_types */
  $quantity_types = \Drupal::service('entity_type.manager')->getStorage('quantity_type')->loadMultiple();
  foreach ($quantity_types as $quantity_type) {
    if (!empty($quantity_type->id())) {
      return $quantity_type->id();
    }
  }

  // Otherwise return NULL.
  return NULL;
}
