<?php

namespace Drupal\nodehive_area_fragment\Form;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form controller for the area edit forms.
 */
class AreaForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $space_id = $this->getRequest()->query->get('nodehive_space');

    if ($space_id && $this->operation == 'add') {

      $space = $this->entityTypeManager
        ->getStorage("nodehive_space")
        ->load($space_id);

      if ($space) {
        $form['space_id']['widget']['#default_value'] = [$space->id()];
      }
    }
    unset($form['machine_name']);

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this->buildEntity($form, $form_state);
    $values = $form_state->getValues();
    $label = $values['label'][0]['value'];

    // @todo Make it more robust.
    $machine_name = strtolower($label);
    if ($entity->isNew()) {
      $form_state->setValue('machine_name', [0 => ['value' => $machine_name]]);
    }

    // The entity was validated.
    $entity->setValidationRequired(FALSE);
    $form_state->setTemporaryValue('entity_validated', TRUE);
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $space_id = $this->getRequest()->query->get('nodehive_space');
    $space = NULL;

    if ($space_id) {
      $space = $this->entityTypeManager->getStorage("nodehive_space")->load($space_id);
    }

    if ($this->operation == "add") {
      $uid = $this->currentUser()->id();
      $this->entity->uid = ['target_id' => $uid];
    }

    $status = parent::save($form, $form_state);

    $entity = $this->entity;
    if ($status == SAVED_UPDATED) {
      $this->messenger()
        ->addMessage(
        $this->t(
          'The area %area has been updated.',
          [
            '%area' => $entity->toLink()->toString(),
          ]
        )
      );
    }
    else {
      $this->messenger()
        ->addMessage(
          $this->t(
          'The area %area has been added.',
          [
            '%area' => $entity->toLink()->toString(),
          ]
        )
          );
    }

    Cache::invalidateTags($this->entity->getCacheTags());

    $referenced_spaces = $this->entity->space_id->referencedEntities();
    foreach ($referenced_spaces as $ref_space) {
      Cache::invalidateTags($ref_space->getCacheTags());
    }

    if ($space) {
      $form_state->setRedirect(
        'entity.nodehive_area.space_collection',
        [
          "nodehive_space" => $space_id,
        ],
      );
    }
    else {
      $form_state->setRedirect(
        'entity.nodehive_area.collection',
        [
          "nodehive_area" => $this->entity->id(),
        ],
      );
    }
    return $status;
  }

}
