<?php

namespace Drupal\nodehive_core;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\system\MenuInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Provides a helper methods to deal with menu entity.
 */
class MenuHelper implements MenuHelperInterface {

  use StringTranslationTrait;

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

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

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

  /**
   * Constructs an MenuHelper object.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   */
  public function __construct(
    AccountProxyInterface $current_user,
    EntityTypeManagerInterface $entity_type_manager,
    RequestStack $request_stack,
  ) {
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function alterMenuForm(array &$form, FormStateInterface $form_state): void {
    /** @var \Drupal\System\MenuInterface $menu_entity */
    $menu_entity = $form_state->getFormObject()->getEntity();
    if (in_array($menu_entity->id(), MenuHelperInterface::ADMIN_MENUS)) {
      return;
    }

    $saved_default_values = $this->getSpaceFieldValue($menu_entity);

    $options = [];
    foreach ($this->entityTypeManager->getStorage("nodehive_space")->loadMultiple() as $space) {
      $options[$space->id()] = $space->label();
    }

    $default_values = [];
    if ($saved_default_values) {
      $default_values = $saved_default_values;
    }
    elseif ($space_id = $this->requestStack->getCurrentRequest()->query->get('space')) {
      $default_values = [$space_id => $space_id];
    }

    $space_reference_field = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Space'),
      '#options' => $options,
      '#default_value' => $default_values,
      '#description' => $this->t('The space, that this content will appear on.'),
      '#weight' => 1,
    ];

    $form['links']['#weight'] = 2;
    $form["nodehive_space"] = $space_reference_field;
    $form['actions']['submit']['#submit'][] = [$this, "saveMenuForm"];
  }

  /**
   * {@inheritdoc}
   */
  public function saveMenuForm(array &$form, FormStateInterface $form_state): void {
    /** @var \Drupal\System\MenuInterface $menu_entity */
    $menu_entity = $form_state->getFormObject()->getEntity();
    $space_reference = array_filter($form_state->getValue("nodehive_space"));

    $saved = $this->getSpaceFieldValue($menu_entity);
    if (!$space_reference && !$saved) {
      return;
    }

    $new_values = [];
    if ($space_reference) {
      foreach ($space_reference as $id) {
        $new_values[$id] = $id;
      }
    }

    $saved = $new_values;

    $menu_entity->setThirdPartySetting("nodehive_core", "nodehive_space_field", $saved);
    $menu_entity->save();
  }

  /**
   * {@inheritdoc}
   */
  public function getSpaceFieldValue(MenuInterface $menu): array {
    return $menu->getThirdPartySetting("nodehive_core", "nodehive_space_field", []);
  }

}
