<?php

/**
 * @file
 * Contains farm_group.module.
 */

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

/**
 * Implements hook_entity_base_field_info().
 */
function farm_group_entity_base_field_info(EntityTypeInterface $entity_type) {
  \Drupal::moduleHandler()->loadInclude('farm_group', 'inc', 'farm_group.base_fields');
  switch ($entity_type->id()) {

    // Build asset base fields.
    case 'asset':
      return farm_group_asset_base_fields();

    // Build log base fields.
    case 'log':
      return farm_group_log_base_fields();

    default:
      return [];
  }
}

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

  // Prevent creating circular group memberships.
  if ($entity_type->id() == 'log' && !empty($fields['asset'])) {
    $fields['asset']->addConstraint('CircularGroupMembership');
  }
}

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

  // Check if the form has the required group fields.
  if (isset($form['group']) && isset($form['is_group_assignment'])) {

    // Set the visible state of the log.group field.
    // Only display if is_group_assignment is checked.
    $form['group']['#states']['visible'] = [':input[name="is_group_assignment[value]"]' => ['checked' => TRUE]];
  }
}

/**
 * Implements hook_farm_ui_theme_region_items().
 */
function farm_group_farm_ui_theme_region_items(string $entity_type) {
  $region_items = [];
  if ($entity_type == 'asset') {
    $region_items = [
      'top' => [],
      'first' => [],
      'second' => [
        'group',
      ],
      'bottom' => [],
    ];
  }
  return $region_items;
}
