<?php

/**
 * @file
 * Contains wxt_ext_user.module.
 */

use Drupal\Core\Session\AccountInterface;
use Drupal\shortcut\Entity\Shortcut;
use Drupal\user\Entity\User;

/**
 * Implements hook_install().
 */
function wxt_ext_user_install() {
  // Enable default permissions for system roles.
  user_role_grant_permissions(AccountInterface::ANONYMOUS_ROLE, [
    'access comments',
    'access user profiles',
  ]);
  user_role_grant_permissions(AccountInterface::AUTHENTICATED_ROLE, [
    'access comments',
    'post comments',
    'access user profiles',
  ]);

  // Assign user 1 the "administrator" role.
  if ($user = User::load(1)) {
    $user->roles[] = 'administrator';
    $user->save();
  }

  // Allow authenticated users to use shortcuts.
  user_role_grant_permissions(AccountInterface::AUTHENTICATED_ROLE, ['access shortcuts']);

  if (!\Drupal::service('config.installer')->isSyncing()) {

    // Populate the default shortcut set.
    $shortcut = Shortcut::create(
      [
        'shortcut_set' => 'default',
        'title' => t('Add content'),
        'weight' => -20,
        'link' => ['uri' => 'internal:/node/add'],
      ]
    );
    $shortcut->save();

    $shortcut = Shortcut::create(
      [
        'shortcut_set' => 'default',
        'title' => t('All content'),
        'weight' => -20,
        'link' => ['uri' => 'internal:/admin/content'],
      ]
    );
    $shortcut->save();

    $shortcut = Shortcut::create(
      [
        'shortcut_set' => 'default',
        'title' => t('All files'),
        'weight' => -19,
        'link' => ['uri' => 'internal:/admin/content/files'],
      ]
    );
    $shortcut->save();
  }

  // Add the First and Last Name fields to the user entity form display.
  \Drupal::service('entity_display.repository')
    ->getFormDisplay('user', 'user', 'default')
    ->setComponent('field_first_name', [
      'type' => 'string_textfield',
    ])
    ->setComponent('field_last_name', [
      'type' => 'string_textfield',
    ])
    ->save();

  // Add values for the First and Last name fields to the admin user.
  if ($user = User::load(1)) {
    $user->set('field_first_name', 'Super');
    $user->set('field_last_name', 'Admin');
    $user->save();
  }
}

/**
 * Implements hook_update_N().
 */
function wxt_ext_user_update_8100() {
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  // Update field storage definitions for user's first and last name fields.
  if ($user_first_name_field = $definition_update_manager->getFieldStorageDefinition('field_first_name', 'user')) {
    $definition_update_manager->updateFieldStorageDefinition($user_first_name_field);
  }
  if ($user_last_name_field = $definition_update_manager->getFieldStorageDefinition('field_last_name', 'user')) {
    $definition_update_manager->updateFieldStorageDefinition($user_last_name_field);
  }
}
