<?php

/**
 * @file
 * Contains farm_birth.module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

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

  // Only proceed if the mother and asset fields exist.
  if (empty($form['mother']) || empty($form['asset'])) {
    return;
  }

  // Rename the asset field to Children.
  $form['asset']['widget']['#title'] = t('Children');
}

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function farm_birth_log_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {

  // Only alter birth logs.
  if ($entity->bundle() != 'birth') {
    return;
  }

  // Rename the asset field to Children.
  if (!empty($build['asset'])) {
    $build['asset']['#title'] = t('Children');
  }
}

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function farm_birth_asset_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {

  // Only alter animal assets.
  if ($entity->bundle() != 'animal') {
    return;
  }

  // Add a link to the asset's birth log.
  if (!empty($build['birthdate'][0])) {
    /** @var \Drupal\Core\Entity\EntityStorageInterface $log_storage */
    $log_storage = \Drupal::service('entity_type.manager')->getStorage('log');
    $log_ids = $log_storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'birth')
      ->condition('asset', $entity->id())
      ->execute();

    // Render a link to the log with a title of the timestamp field value.
    if (!empty($log_ids)) {
      $title = $build['birthdate'][0];
      $build['birthdate'][0] = [
        '#type' => 'link',
        '#title' => $title,
        '#url' => Url::fromRoute('entity.log.canonical', ['log' => reset($log_ids)]),
      ];
    }
  }
}

/**
 * Implements hook_entity_base_field_info_alter().
 */
function farm_birth_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  /** @var \Drupal\field\Entity\FieldConfig[] $fields */

  // Validate that only one birth log references an asset.
  if ($entity_type->id() == 'log' && !empty($fields['asset'])) {
    $fields['asset']->addConstraint('UniqueBirthLog');
  }
}
