<?php

namespace Drupal\nodehive_core_space_dashboard\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Space visit link redirect controller.
 */
class SpaceVisitLinkRedirectController extends ControllerBase {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new SpaceVisitLinkRedirectController.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')
    );
  }

  /**
   * Redirects a user to the space defined URL.
   */
  public function redirectToSpaceLink() {
    $current_request = $this->requestStack->getCurrentRequest();
    $host = $current_request->getSchemeAndHttpHost();

    // Get referer and fetch the space entity ID.
    $previous_url = $current_request->server->get('HTTP_REFERER');
    $previous_url = str_replace($host, "", $previous_url);
    $previous_url = Url::fromUserInput($previous_url);
    $route_params = $previous_url->getRouteParameters();

    if (!isset($route_params['nodehive_space'])) {
      $this->messenger()->addError('Missing space entity id.');
      return $this->redirect('<front>');
    }

    $nodehive_space = $this->entityTypeManager()
      ->getStorage('nodehive_space')
      ->load($route_params['nodehive_space']);

    if (!$nodehive_space) {
      $this->messenger()->addError('Space entity does not exists.');
      return $this->redirect('<front>');
    }

    $urls = $nodehive_space->get("space_url")->getValue();
    if (!$urls) {
      $this->messenger()->addError('Missing space link.');
      return $this->redirect('<front>');
    }
    $url = end($urls);

    return new TrustedRedirectResponse($url['uri']);
  }

}
