<?php

namespace Drupal\castorcito\Form;

use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Castorcito category form.
 */
class CastorcitoCategoryForm extends EntityForm {

  /**
   * The entity being used by this form.
   *
   * @var \Drupal\castorcito\CastorcitoCategoryInterface
   */
  protected $entity;

  /**
   * The castorcito category entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $categoryStorage;

  /**
   * Constructs a base class for castorcito category add and edit forms.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $category_storage
   *   The castorcito category entity storage.
   */
  public function __construct(EntityStorageInterface $category_storage) {
    $this->categoryStorage = $category_storage;
  }

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

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

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

    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $this->entity->label(),
      '#required' => TRUE,
    ];

    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $this->entity->id(),
      '#machine_name' => [
        'exists' => [$this->categoryStorage, 'load'],
      ],
      '#disabled' => !$this->entity->isNew(),
    ];

    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Description'),
      '#default_value' => $this->entity->get('description'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state): int {
    $result = parent::save($form, $form_state);
    $message_args = ['%label' => $this->entity->label()];
    $this->messenger()->addStatus(
      match($result) {
        \SAVED_NEW => $this->t('Created new castorcito category %label.', $message_args),
        \SAVED_UPDATED => $this->t('Updated castorcito category %label.', $message_args),
      }
    );
    $form_state->setRedirectUrl($this->entity->toUrl('collection'));
    return $result;
  }

}
