<?php

namespace Drupal\reader\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\reader\ReaderInterface;
use Drupal\user\UserDataInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ReaderSearchForm extends FormBase {

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

  /**
   * ReaderSearchForm constructor.
   *
   * @param \Drupal\user\UserDataInterface $user_data
   *   The user data service.
   */
  public function __construct(UserDataInterface $user_data) {
    $this->userData = $user_data;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'reader_search_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    // Default to either the module from the default channel or on the reader
    // timeline route.
    $route_name = $this->getRouteMatch()->getRouteName();
    if ($route_name == 'reader.timeline') {
      $module = $this->getRouteMatch()->getRawParameter('module');
    }
    else {
      $settings = $this->userData->get('reader', $this->currentUser()->id(), 'settings');
      $default_timeline = !empty($settings['default_timeline']) ? $settings['default_timeline'] : '';
      if (!empty($default_timeline)) {
        [$module,] = explode(ReaderInterface::SEPARATOR, $default_timeline);
      }
    }

    if (!isset($module)) {
      return ['#markup' => '<p>' . $this->t('Select a default timeline in your settings for a default search.') . '</p>'];
    }

    $form['keyword'] = [
      '#type' => 'textfield',
      '#placeholder' => $this->t('Search'),
      '#title' => $this->t('Search'),
      '#title_display' => 'hidden',
      '#required' => TRUE,
      '#default_value' => !empty($_GET['keyword']) ? $_GET['keyword'] : '',
    ];

    $form['module'] = [
      '#type' => 'value',
      '#value' => $module,
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#suffix' => '<i class="search-submit fa fa-search" ></i>'
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $args = ['keyword' => $form_state->getValue('keyword')];
    if ($module = $form_state->getValue('module')) {
      $args['module'] = $module;
    }
    $form_state->setRedirect('reader.search', [], ['query' => $args]);
  }

}
