<?php

namespace Drupal\reader\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\reader\ReaderInterface;
use Drupal\user\UserDataInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides the actions block.
 *
 * @Block(
 *   id = "reader_actions",
 *   admin_label = @Translation("Reader actions"),
 *   category = @Translation("Reader")
 * )
 */
class Actions extends BlockBase implements ContainerFactoryPluginInterface {

  use RedirectDestinationTrait;

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

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

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $userData;

  /**
   * Actions constructor
   *
   * @param array $configuration
   *   The plugin configuration, i.e. an array with configuration values keyed
   *   by configuration option name. The special key 'context' may be used to
   *   initialize the defined contexts by setting it to an array of context
   *   values keyed by context names.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match, ConfigFactoryInterface $config_factory, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, UserDataInterface $user_data) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->routeMatch = $route_match;
    $this->configFactory = $config_factory;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->moduleHandler = $module_handler;
    $this->userData = $user_data;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_route_match'),
      $container->get('config.factory'),
      $container->get('current_user'),
      $container->get('entity_type.manager'),
      $container->get('module_handler'),
      $container->get('user.data')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $module = '';
    $id = '';
    $links = [];

    if (!$this->currentUser->hasPermission('access reader')) {
      return [];
    }

    // Set module and id.
    $route_name = $this->routeMatch->getRouteName();
    if ($route_name == 'reader.timeline') {
      $module = $this->routeMatch->getParameter('module');
      $id = $this->routeMatch->getParameter('id');
    }
    elseif ($route_name == 'reader.home') {
      $settings = $this->userData->get('reader', $this->currentUser->id(), 'settings');
      $default_timeline = !empty($settings['default_timeline']) ? $settings['default_timeline'] : '';
      if (!empty($default_timeline)) {
        [$module, $id] = explode(ReaderInterface::SEPARATOR, $default_timeline);
      }
    }

    if (!empty($module) && !empty($id)) {
      $function = strtr($module, '-', '_') . '_reader_timeline_actions';
      if (function_exists($function)) {
        $response = $function($id);
        if (!empty($response)) {
          foreach ($response as $a) {
            $links[] = [
              'url' => Url::fromRoute('reader.timeline.action', ['module' => strtr($module, '_', '-'), 'action' => $a['action'], 'id' => $id], ['query' => $this->getDestinationArray()]),
              'title' => $a['title'],
            ];
          }
        }
      }
    }

    // Add content/comment links.
    if ($route_name == 'reader.content' && $this->moduleHandler->moduleExists('comment')) {
      $links[] = [
        'url' => Url::fromRoute('reader.content', [], ['query' => ['content' => 'content']]),
        'title' => $this->t('Content'),
      ];
      $links[] = [
        'url' => Url::fromRoute('reader.content', [], ['query' => ['content' => 'comment']]),
        'title' => $this->t('Comments'),
      ];
    }

    $links[] = [
      'url' => Url::fromRoute('user.logout', [], ['attributes' => ['class' => ['reader-logout']], 'query' => ['destination' => Url::fromRoute('reader.home')->toString()]]),
      'title' => $this->t('Logout'),
    ];

    return [
      '#theme' => 'links__reader_actions',
      '#links' => $links,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

}
