<?php

namespace Drupal\nodehive_area_fragment\Form;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Provides a form for deleting a fragment.
 */
class FragmentDeleteForm extends ContentEntityDeleteForm {

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Check if used in any of the areas.
    $areas_query = $this->entityTypeManager
      ->getStorage('nodehive_area')
      ->getQuery();

    $areas_query
      ->accessCheck(FALSE)
      ->condition('fragment_id', [$this->entity->id()], "IN");
    $areas = $areas_query->execute();

    if (count($areas) >= 1) {
      // Load the areas.
      $areas = $this->entityTypeManager
        ->getStorage('nodehive_area')
        ->loadMultiple($areas);

      foreach ($areas as $area) {
        $manage_fragments_url = Url::fromRoute(
          "entity.nodehive_area.manage_fragments",
          [
            'nodehive_area' => $area->id(),
          ],
        );

        $this->messenger()->addError(
          $this->t(
            "Fragment is assigned to the area <a href='@link'>@label</a>, please remove all references
            before deleting a fragment.",
            [
              "@link" => $manage_fragments_url->toString(),
              "@label" => $area->label(),
            ],
          )
        );
      }
      return FALSE;
    }

    Cache::invalidateTags($this->entity->getCacheTags());
    $space_id = $this->getRequest()->query->get('nodehive_space');
    if ($space_id) {
      $space = $this->entityTypeManager
        ->getStorage("nodehive_space")
        ->load($space_id);

      Cache::invalidateTags($space->getCacheTags());
    }

    return parent::submitForm($form, $form_state);
  }

}
