<?php

namespace Drupal\translatable_config_pages\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form controller for the translatable config pages entity edit forms.
 */
class TranslatableConfigPagesForm extends ContentEntityForm {

  /**
   * Router builder.
   *
   * @var \Drupal\Core\Routing\RouteBuilderInterface
   */
  protected RouteBuilderInterface $routerBuilder;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, RouteBuilderInterface $router_builder) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->routerBuilder = $router_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.repository'),
      $container->get('entity_type.bundle.info'),
      $container->get('datetime.time'),
      $container->get('router.builder'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $result = parent::save($form, $form_state);

    $entity = $this->getEntity();

    $message_arguments = ['%label' => $entity->toLink()->toString()];

    switch ($result) {
      case SAVED_NEW:
        $this->messenger()
          ->addStatus($this->t('Config "%label" has been created.', $message_arguments));

        // Rebuild routes to show new menu items.
        $this->routerBuilder->rebuild();

        break;

      case SAVED_UPDATED:
        $this->messenger()
          ->addStatus($this->t('The config "%label" has been updated.', $message_arguments));
        break;
    }

    $form_state->setRedirect('entity.translatable_config_pages.edit_form', ['translatable_config_pages' => $entity->id()]);

    return $result;
  }

}
