<?php

namespace Drupal\nodehive_area_fragment\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\nodehive_core\SpaceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Returns responses for fragment entity routes.
 */
class FragmentController extends ControllerBase {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new EntityController.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    EntityTypeBundleInfoInterface $entity_type_bundle_info,
    RendererInterface $renderer,
  ) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('entity_type.bundle.info'),
      $container->get('renderer'),
    );
  }

  /**
   * Add fragment page.
   *
   * @param \Drupal\nodehive_core\SpaceInterface $nodehive_space
   *   The space entity.
   *
   * @return array
   *   A renderable array.
   */
  public function addFragmentPage(?SpaceInterface $nodehive_space = NULL) {
    $entity_type = $this->entityTypeManager->getDefinition('nodehive_fragment');
    $bundles = $this->entityTypeBundleInfo->getBundleInfo('nodehive_fragment');

    $bundle_entity_type_id = $entity_type->getBundleEntityType();
    $build = [
      '#theme' => 'entity_add_list',
      '#bundles' => [],
    ];

    $bundle_argument = $bundle_entity_type_id;
    $bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);
    $bundle_entity_type_label = $bundle_entity_type->getSingularLabel();
    $build['#cache']['tags'] = $bundle_entity_type->getListCacheTags();

    // Build the message shown when there are no bundles.
    $link_text = $this->t('Add a new @entity_type.', ['@entity_type' => $bundle_entity_type_label]);
    $link_route_name = 'entity.' . $bundle_entity_type->id() . '.add_form';
    $build['#add_bundle_message'] = $this->t('There is no @entity_type yet. @add_link', [
      '@entity_type' => $bundle_entity_type_label,
      '@add_link' => Link::createFromRoute($link_text, $link_route_name)->toString(),
    ]);

    // Filter out the bundles the user doesn't have access to.
    $access_control_handler = $this->entityTypeManager
      ->getAccessControlHandler('nodehive_fragment');

    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);
    }

    // Prepare the #bundles array for the template.
    foreach ($bundles as $bundle_name => $bundle_info) {
      $build['#bundles'][$bundle_name] = [
        'label' => $bundle_info['label'],
        'description' => $bundle_info['description'] ?? '',
        'add_link' => Link::createFromRoute(
          $bundle_info['label'],
          'entity.nodehive_fragment.add_form',
          [
            $bundle_argument => $bundle_name,
            'nodehive_space' => $nodehive_space->id(),
          ]),
      ];
    }

    return $build;
  }

  /**
   * Redirects from /space/{id}/fragments to /space/{id}/content/fragments.
   *
   * @param \Drupal\nodehive_core\SpaceInterface $nodehive_space
   *   The space entity.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response.
   */
  public function redirectToContentFragments(SpaceInterface $nodehive_space) {
    $url = Url::fromRoute('nodehive_core_space_dashboard.content_fragments', [
      'nodehive_space' => $nodehive_space->id(),
    ]);
    return new RedirectResponse($url->toString(), 301);
  }

}
