<?php

namespace Drupal\nodehive_core\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Settings form for local configurator.
 */
class NodeHiveLocalSettingsForm extends ConfigFormBase {

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

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

  /**
   * Constructs a new NodeHiveLocalSettingsForm.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The typed config manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    TypedConfigManagerInterface $typedConfigManager,
    EntityTypeManagerInterface $entity_type_manager,
    LanguageManagerInterface $language_manager,
  ) {
    parent::__construct($config_factory, $typedConfigManager);
    $this->entityTypeManager = $entity_type_manager;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('entity_type.manager'),
      $container->get('language_manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'nodehive_core.local_settings',
    ];
  }

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

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

    $spaces = $this->entityTypeManager
      ->getStorage('nodehive_space')
      ->loadMultiple();

    $space_options = [];
    foreach ($spaces as $space) {
      $space_options[$space->id()] = $space->label();
    }

    unset($form['actions']);
    $request = $this->getRequest();

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

    $form['selector_container']['space'] = [
      '#type' => 'select',
      '#title' => $this->t('Select a space'),
      '#options' => $space_options,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => [$this, 'reloadEnvData'],
        'wrapper' => 'env-data-wrapper',
      ],
    ];

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

    $selected_language = $request->query->get('langcode');
    $form['selector_container']['language'] = [
      '#type' => 'select',
      '#title' => $this->t('Select default language'),
      '#options' => $languages_options,
      '#default_value' => $selected_language,
    ];

    $host = $request->getHost();
    $form['host'] = [
      '#type' => 'hidden',
      '#value' => $host,
    ];

    $form['env_data'] = [
      '#theme' => 'nodehive_local_settings',
      '#base_url' => $host,
      '#space_url' => NULL,
      '#space_id' => NULL,
      '#language' => NULL,
      '#homepage' => NULL,
      '#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.
   *
   * @param array $form
   *   Entire form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Current form state.
   */
  public function reloadEnvData(array &$form, FormStateInterface $form_state) {
    $selected_space = $form_state->getValue('space');
    $selected_langcode = $form_state->getValue('language');
    $host = $form_state->getValue('host');

    if ($selected_space) {
      $space = $this->entityTypeManager->getStorage('nodehive_space')
        ->load($selected_space);

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

      return [
        '#theme' => 'nodehive_local_settings',
        '#base_url' => $host,
        '#space_url' => $space->space_url->uri,
        '#space_id' => $selected_space,
        '#language' => $selected_langcode,
        '#homepage' => $homepage_node,
        '#weight' => 100,
        '#prefix' => '<div id="env-data-wrapper">',
        '#suffix' => '</div>',
      ];
    }

    return [
      '#theme' => 'nodehive_local_settings',
      '#base_url' => $host,
      '#space_url' => NULL,
      '#space_id' => NULL,
      '#language' => NULL,
      '#homepage' => NULL,
      '#weight' => 100,
      '#prefix' => '<div id="env-data-wrapper">',
      '#suffix' => '</div>',
    ];
  }

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

}
