<?php

/**
 * @file
 * ID tag module.
 */

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Implements hook_entity_base_field_info().
 */
function farm_id_tag_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];

  // Add ID tag field to assets.
  if ($entity_type->id() == 'asset') {
    $field_info = [
      'type' => 'id_tag',
      'label' => t('ID tags'),
      'description' => t('List any identification tags that this asset has. Use the fields below to describe the type, location, and ID of each.'),
      'multiple' => TRUE,
      'weight' => [
        'form' => 50,
        'view' => 0,
      ],
    ];
    $fields['id_tag'] = \Drupal::service('farm_field.factory')->baseFieldDefinition($field_info);

    // Add an ID tag type constraint to ID tag fields to ensure valid type.
    $fields['id_tag']->addConstraint('IdTagType');
  }

  return $fields;
}

/**
 * ID tag type options helper.
 *
 * @param string $bundle
 *   The asset bundle to get allowed values for.
 *
 * @return array
 *   Returns an array of allowed values for use in form select options.
 */
function farm_id_tag_type_options(string $bundle) {
  /** @var \Drupal\farm_id_tag\Entity\FarmIDTagTypeInterface[] $types */
  $types = \Drupal::entityTypeManager()->getStorage('tag_type')->loadMultiple();
  $options = [];
  foreach ($types as $id => $type) {
    $bundles = $type->getBundles();
    if (empty($bundles) || in_array($bundle, $bundles)) {
      $options[$id] = $type->getLabel();
    }
  }
  return $options;
}

/**
 * Implements hook_theme().
 */
function farm_id_tag_theme() {
  return [
    'field__id_tag' => [
      'template' => 'field--id-tag',
      'base hook' => 'field',
    ],
  ];
}
