<?php

namespace Drupal\nodehive_core_space_dashboard\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\nodehive_core\SpaceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Displays frontend environment variables for a specific space.
 */
class SpaceEnvVarsForm extends FormBase {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

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

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

  /**
   * Constructs a new SpaceEnvVarsForm.
   */
  public function __construct(
    LanguageManagerInterface $language_manager,
    RequestStack $request_stack,
    RouteMatchInterface $route_match,
  ) {
    $this->languageManager = $language_manager;
    $this->requestStack = $request_stack;
    $this->routeMatch = $route_match;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $space = $this->routeMatch->getParameter('nodehive_space');
    if (!$space instanceof SpaceInterface) {
      return $form;
    }

    $request = $this->requestStack->getCurrentRequest();
    $host = $request->getHost();

    $languages = $this->languageManager->getLanguages();
    $languages_options = [];
    foreach ($languages as $language) {
      $languages_options[$language->getId()] = $language->getName();
    }

    $form['selector_container'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['selector-form'],
      ],
    ];

    $form['selector_container']['language'] = [
      '#type' => 'select',
      '#title' => $this->t('Select default language'),
      '#options' => $languages_options,
      '#default_value' => $this->languageManager->getCurrentLanguage()->getId(),
      '#ajax' => [
        'callback' => [$this, 'reloadEnvData'],
        'wrapper' => 'env-data-wrapper',
      ],
    ];

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

    $homepage_node = $space->get('frontpage_node')->target_id;
    if (!$homepage_node) {
      $homepage_node = 'xx';
    }

    $space_url = NULL;
    if ($space->hasField('space_url') && !$space->get('space_url')->isEmpty()) {
      $space_url = $space->get('space_url')->uri;
    }

    $selected_language = $form_state->getValue('language') ?: $this->languageManager->getCurrentLanguage()->getId();

    $form['env_data'] = [
      '#theme' => 'nodehive_local_settings',
      '#base_url' => $host,
      '#space_url' => $space_url,
      '#space_id' => $space->id(),
      '#language' => $selected_language,
      '#homepage' => $homepage_node,
      '#weight' => 100,
      '#prefix' => '<div id="env-data-wrapper">',
      '#suffix' => '</div>',
    ];

    $form['#attached']['library'][] = 'nodehive_core/local-settings';

    return $form;
  }

  /**
   * Ajax callback for reloading the env data.
   */
  public function reloadEnvData(array &$form, FormStateInterface $form_state) {
    return $form['env_data'];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}
