<?php

/**
 * @file
 * Install, update and uninstall functions for the social_event_type module.
 */

use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Config\FileStorage;
use Drupal\field\FieldConfigInterface;
use Drupal\user\Entity\Role;
use Symfony\Component\Yaml\Yaml;

/**
 * Implements hook_install().
 *
 * Perform actions related to the installation of social_event_type.
 */
function social_event_type_install() {
  // Fetch sitemananger role.
  $role = Role::load('sitemanager');
  // Set permission for site manager.
  if ($role instanceof Role) {
    // Set permission.
    $role->grantPermission('set social event type settings');
    $role->grantPermission('edit terms in event_types');
    $role->grantPermission('delete terms in event_types');
    $role->trustData()->save();
  }
}

/**
 * Implements hook_uninstall().
 *
 * Perform actions related to the de-installation of social_event_type.
 */
function social_event_type_uninstall() {
  // Fetch sitemananger role.
  $role = Role::load('sitemanager');
  // Set permission for site manager.
  if ($role instanceof Role) {
    // Set permission.
    $role->revokePermission('set social event type settings');
    $role->revokePermission('edit terms in event_types');
    $role->revokePermission('delete terms in event_types');
    $role->trustData()->save();
  }

  // Also remove the fields and the vocabulary.
  \Drupal::configFactory()->getEditable('field.field.node.event.field_event_type')->delete();
  \Drupal::configFactory()->getEditable('field.storage.node.field_event_type')->delete();
  \Drupal::configFactory()->getEditable('taxonomy.vocabulary.event_types')->delete();
  \Drupal::configFactory()->getEditable('social_event_type.settings')->delete();
}

/**
 * Update label for field_event_type field.
 */
function social_event_type_update_8901() {
  // Load the existing configuration.
  $config_name = 'field.field.node.event.field_event_type';
  $config = \Drupal::configFactory()->getEditable($config_name);
  $config_data = $config->getRawData();

  if (!empty($config_data['label'])) {
    // This to ensure any custom added values are not affected.
    if (strpos($config_data['label'], 'Event type') !== FALSE) {
      $config_data['label'] = 'Type';
    }

    $config->setData($config_data)->save();
    // Make sure we clear cached definitions for the fields.
    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
  }
}

/**
 * Create new field & field storage configuration for new event type icon field.
 */
function social_event_type_update_8902(&$sandbox) {
  $config_file = \Drupal::service('extension.list.module')->getPath('social_event_type') . '/config/static/social_event_type_update_8902.yml';

  if (is_file($config_file)) {
    $sandbox['configs'] = Yaml::parse(file_get_contents($config_file));
    if (!isset($sandbox['total'])) {
      // Count the amount we need to add to cover batching..
      $sandbox['total'] = count($sandbox['configs']);
      $sandbox['current'] = 0;
    }

    $names = array_keys($sandbox['configs']);
    $name = (string) $names[$sandbox['current']++];
    $data = $sandbox['configs'][$name];

    $parts = explode('.', $name);

    switch ($parts[0] . '.' . $parts[1]) {
      case 'field.storage':
        $entity_type = \Drupal::service('config.manager')
          ->getEntityTypeIdByName($name);

        /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $storage */
        $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
        $entity = $storage->createFromStorageRecord($data);
        $entity->save();
        break;

      case 'field.field':
        $field_config = FieldConfig::loadByName($parts[2], $parts[3], $parts[4]);

        if ($field_config instanceof FieldConfigInterface) {
          $field_config->setDescription($data);
        }
        else {
          $field_config = FieldConfig::create($data);
        }

        $field_config->save();
        break;

      default:
        // Fallback similar to before.
        \Drupal::configFactory()
          ->getEditable($name)
          ->setData($data)
          ->save(TRUE);
    }

    $sandbox['#finished'] = $sandbox['current'] / $sandbox['total'];
  }
}

/**
 * Make "Event Types" vocabulary translatable.
 */
function social_event_type_update_11201(): void {
  if (!\Drupal::moduleHandler()->moduleExists('social_content_translation')) {
    return;
  }

  $config_storage = \Drupal::service('config.storage');
  $config_path = \Drupal::service('extension.list.module')->getPath('social_event_type') . '/config/static';
  $source = new FileStorage($config_path);

  $config_storage->write('language.content_settings.taxonomy_term.event_types', (array) $source->read('language.content_settings.taxonomy_term.event_types_11201'));
}
