<?php

/**
 * @file
 * Contains farm_api.module.
 */

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\entity\BundleFieldDefinition;

/**
 * Implements hook_consumers_list_alter().
 *
 * Display the client_id in the list of consumers.
 */
function farm_api_consumers_list_alter(&$data, $context) {
  if ($context['type'] === 'header') {
    $data['client_id'] = t('Client ID');
  }
  elseif ($context['type'] === 'row') {
    $entity = $context['entity'];

    $data['client_id'] = NULL;
    if ($client_id = $entity->get('client_id')->value) {
      $data['client_id'] = $client_id;
    }
  }
}

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

  // Add bundle fields to the consumer entity.
  if ($entity_type->id() == 'consumer') {
    $fields['grant_user_access'] = BundleFieldDefinition::create('boolean')
      ->setLabel(t('Grant user access'))
      ->setDescription(t("Always grant the authorizing user's access to this consumer."))
      ->setSetting('on_label', t('Yes'))
      ->setSetting('off_label', t('No'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 4,
      ]);

    $fields['limit_requested_access'] = BundleFieldDefinition::create('boolean')
      ->setLabel(t('Limit to requested access'))
      ->setDescription(t('Only grant this consumer the scopes requested during authorization.'))
      ->setSetting('on_label', t('Yes'))
      ->setSetting('off_label', t('No'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 4,
      ]);

    $fields['limit_user_access'] = BundleFieldDefinition::create('boolean')
      ->setLabel(t('Limit to user access'))
      ->setDescription(t('Never grant this consumer more access than the authorizing user.'))
      ->setSetting('on_label', t('Yes'))
      ->setSetting('off_label', t('No'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 4,
      ]);

    $fields['allowed_origins'] = BundleFieldDefinition::create('string')
      ->setLabel(t('Allowed origins'))
      ->setDescription(t('Configure CORS origins for this consumer.'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'settings' => [
          'size' => 255,
          'placeholder' => 'https://example.com',
        ],
      ]);
  }

  return $fields;
}
