<?php

namespace Drupal\nodehive_area_fragment\Form;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a form for removing a fragment from a area.
 */
class RemoveFragmentFromArea extends ConfirmFormBase {

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

  /**
   * RemoveFragmentFormArea constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
  ) {
    $this->entityTypeManager = $entity_type_manager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $area_id = $this->getRouteMatch()->getParameter('nodehive_area');
    $area = $this->entityTypeManager->getStorage('nodehive_area')->load($area_id);
    $fragment_id = $this->getRouteMatch()->getParameter('nodehive_fragment');

    $attached_fragments = $area->fragment_id->getValue();
    $value = [];
    foreach ($attached_fragments as $item) {
      if ($item['target_id'] != $fragment_id) {
        $value[] = $item['target_id'];
      }
    }
    $area->fragment_id = $value;
    $area->save();

    $form_state->setRedirect(
      'entity.nodehive_area.manage_fragments',
      [
        "nodehive_area" => $area_id,
      ],
    );

    $this->messenger()
      ->addMessage($this->t('The fragment has been removed.'));
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to remove the fragment from the area?');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this->t('Remove');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    $space_id = $this->getRequest()->query->get('nodehive_space');

    if ($space_id) {
      return new Url(
        'entity.nodehive_area.space_collection',
        [
          "nodehive_space" => $space_id,
        ],
      );
    }

    return new Url(
      'entity.nodehive_area.collection',
    );
  }

}
