<?php

namespace Drupal\pagedesigner\EventSubscriber;

use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Event subscriber to disable css and js aggregation in editing mode.
 *
 * In editing mode, the pagedesigner needs to
 * selectively load javascript and css. Aggregation would prevent this.
 */
class InitSubscriber implements EventSubscriberInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $user = NULL;


  /**
   * The current route.
   *
   * @var \Drupal\Core\Routing\CurrentRouteMatch
   */
  protected $currentRoute = NULL;


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

  /**
   * Create the InitSubscriber.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $user
   *   The current user.
   * @param \Drupal\Core\Routing\CurrentRouteMatch $currentRoute
   *   The current route.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(AccountProxyInterface $user, CurrentRouteMatch $currentRoute, RequestStack $requestStack) {
    $this->user = $user;
    $this->currentRoute = $currentRoute;
    $this->requestStack = $requestStack;
  }

  /**
   * Redirect old pagedesigner url to new route.
   *
   *   The event.
   */
  public function redirectOldUrl(RequestEvent $event) {
    if (!$this->user->isAnonymous() && $this->requestStack->getCurrentRequest()->query->get('pd') == 1) {
      $nid = $this->currentRoute->getRawParameter('node');
      if (\is_numeric($nid)) {
        $event->setResponse(new RedirectResponse(Url::fromRoute(
          'pagedesigner.node.edit_mode',
          ['node' => $nid])->toString()
        ));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => [['redirectOldUrl', 30]],
    ];
  }

}
