<?php

/**
 * @file
 * Install, update and uninstall functions for the Varbase installation profile.
 */

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Yaml\Yaml;
use Drupal\Core\Config\InstallStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Config\FileStorage;
use Vardot\Entity\EntityDefinitionUpdateManager;

/**
 * Implements hook_install().
 *
 * Perform actions to set up the site for this profile.
 *
 * @see system_install()
 */
function varbase_install() {

  // Install optional configs.
  $config_installer = \Drupal::service('config.installer');
  $optional_install_path = \Drupal::service('extension.list.profile')->getPath('varbase') . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
  if (is_dir($optional_install_path)) {
    // Install any optional config the profile provides.
    $storage = new FileStorage($optional_install_path, StorageInterface::DEFAULT_COLLECTION);
    $config_installer->installOptionalConfig($storage, '');
    // Have the .settings.yml configs into the active config.
    $settings_config_files = \Drupal::service('file_system')->scanDirectory($optional_install_path, '/^.*(settings.yml)$/i');
    if (isset($settings_config_files) && is_array($settings_config_files)) {
      foreach ($settings_config_files as $settings_config_file) {
        $settings_config_file_content = file_get_contents(DRUPAL_ROOT . '/' . $settings_config_file->uri);
        $settings_config_file_data = (array) Yaml::parse($settings_config_file_content);
        $config_factory = \Drupal::configFactory()->getEditable($settings_config_file->name);
        $config_factory->setData($settings_config_file_data)->save(TRUE);
      }
    }
  }
  // ---------------------------------------------------------------------------
  // Set front page to "node".
  \Drupal::configFactory()->getEditable('system.site')->set('page.front', '/node')->save(TRUE);

  // Disable Aggregate CSS files.
  \Drupal::configFactory()->getEditable('system.performance')->set('css.preprocess', 0)->save(TRUE);

  // Disable Aggregate JavaScript files
  \Drupal::configFactory()->getEditable('system.performance')->set('js.preprocess', 0)->save(TRUE);

  // Entity updates to clear up any mismatched entity and/or field definitions
  // And Fix changes were detected in the entity type and field definitions.
  \Drupal::classResolver()
    ->getInstanceFromDefinition(EntityDefinitionUpdateManager::class)
    ->applyUpdates();

  // ---------------------------------------------------------------------------
  // Remove all leftover configs related to varbase_installer_theme.
  $all_configs = \Drupal::service('config.storage')->listAll();

  $matches = array_filter($all_configs, function ($name) {
    return str_contains($name, 'varbase_installer_theme');
  });

  foreach ($matches as $config_name) {
    \Drupal::configFactory()->getEditable($config_name)->delete();
  }
  // ---------------------------------------------------------------------------
  // Clear cached definitions.
  \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
  \Drupal::service('plugin.manager.block')->clearCachedDefinitions();

  \Drupal::service('plugin.manager.menu.contextual_link')->clearCachedDefinitions();
  \Drupal::service('plugin.manager.menu.local_task')->clearCachedDefinitions();
  \Drupal::service('plugin.manager.menu.local_action')->clearCachedDefinitions();

  // Invalidating.
  \Drupal::service('cache.menu')->invalidateAll();
  \Drupal::service('cache.render')->invalidateAll();

  // Rebuilding.
  \Drupal::service('plugin.manager.menu.link')->rebuild();

  // Rebuild permissions. The content access permissions need to be rebuilt.
  node_access_rebuild();

  // Rebuild the menu router based on all rebuilt data.
  // Important: This rebuild must happen last, so the menu router is guaranteed
  // to be based on up to date information.
  \Drupal::service('router.builder')->rebuild();

  // Resets all static caches.
  drupal_static_reset();

  // Full flash and clear cash and rebuilding newly created routes.
  // After install of extra modules by install: in the .info.yml files.
  // In Varbase profile and all Varbase components.
  // ---------------------------------------------------------------------------
  // * Necessary initialization for the entire system.
  // * Account for changed config by the end install.
  // * Flush all persistent caches.
  // * Flush asset file caches.
  // * Wipe the Twig PHP Storage cache.
  // * Rebuild module and theme data.
  // * Clear all plugin caches.
  // * Rebuild the menu router based on all rebuilt data.
  drupal_flush_all_caches();

  // If Varbase Tour were enabled then redirect to the homepage with active tour.
  if (isset($GLOBALS['homepage_with_varbase_tour'])
    && $GLOBALS['homepage_with_varbase_tour'] == TRUE) {
    $homepage_with_tour = "/?tour";
    $response = new RedirectResponse($homepage_with_tour);
    $response->send();
    exit;
  }
}
