<?php

namespace Drupal\translatable_config_pages\Entity\Controller;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\Controller\EntityController;
use Drupal\Core\Link;

/**
 * Extends EntityController.
 */
class TranslatableConfigPagesEntityController extends EntityController {

  /**
   * {@inheritdoc}
   */
  public function addPage($entity_type_id) {
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
    $bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
    $bundle_key = $entity_type->getKey('bundle');
    $bundle_entity_type_id = $entity_type->getBundleEntityType();
    $build = [
      '#theme' => 'entity_add_list',
      '#bundles' => [],
    ];
    if ($bundle_entity_type_id) {
      $bundle_argument = $bundle_entity_type_id;
      $bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);
      $build['#cache']['tags'] = $bundle_entity_type->getListCacheTags();

      // Build the message shown when there are no bundles.
      $build['#add_bundle_message'] = $this->t('You cannot add more configuration pages. Please edit the existing configuration pages.');
      // Filter out the bundles the user doesn't have access to.
      $access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
      foreach ($bundles as $bundle_name => $bundle_info) {
        $access = $access_control_handler->createAccess($bundle_name, NULL, [], TRUE);
        if (!$access->isAllowed()) {
          unset($bundles[$bundle_name]);
        }
        $this->renderer->addCacheableDependency($build, $access);
      }
      // Add descriptions from the bundle entities.
      $bundles = $this->loadBundleDescriptions($bundles, $bundle_entity_type);
    }
    else {
      $bundle_argument = $bundle_key;
    }

    $form_route_name = 'entity.' . $entity_type_id . '.add_form';

    foreach ($bundles as $bundle_name => $bundle_info) {
      try {
        if (!$this->exitsBundlesContents($bundle_name)) {
          $build['#bundles'][$bundle_name] = [
            'label' => $bundle_info['label'],
            'description' => $bundle_info['description'] ?? '',
            'add_link' => Link::createFromRoute($bundle_info['label'], $form_route_name, [$bundle_argument => $bundle_name]),
          ];
        }
      }
      catch (InvalidPluginDefinitionException | PluginNotFoundException $e) {
        // Do nothing.
      }
    }

    return $build;
  }

  /**
   * Check if already exists contents of a config_page type.
   *
   * @param string $bundle
   *   The config_page type.
   *
   * @return bool
   *   The check.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function exitsBundlesContents(string $bundle): bool {
    $configPages = $this->entityTypeManager->getStorage('translatable_config_pages')
      ->loadByProperties(['bundle' => $bundle]);
    return count($configPages);
  }

}
