<?php

namespace Drupal\nodehive_area_fragment\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form controller for the fragment edit forms.
 */
class FragmentForm extends ContentEntityForm {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs a ContentEntityForm object.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   Language manager.
   */
  public function __construct(
    EntityRepositoryInterface $entity_repository,
    EntityTypeBundleInfoInterface $entity_type_bundle_info,
    TimeInterface $time,
    LanguageManagerInterface $language_manager,
  ) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->entityRepository = $entity_repository;
    $this->languageManager = $language_manager;
  }

  /**
   * {@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('language_manager')
    );
  }

  /**
   * {@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()];
      }
    }

    $form['bundle'] = [
      '#type' => 'item',
      '#title' => $this->t(
        "Type: @bundle",
        [
          '@bundle' => $this->entity->bundle(),
        ]
      ),
      '#weight' => -10,
    ];

    $form['uid']['#access'] = FALSE;

    $languages = $this->languageManager->getLanguages();
    $langcodes = [];
    foreach ($languages as $langcode => $language) {
      $langcodes[$langcode] = $language->getName();
    }

    if (count($languages) > 1) {
      $saved_language = $this->entity->language()->getId();
      $form['default_language'] = [
        '#type' => 'select',
        '#title' => $this->t("Default Language"),
        '#options' => $langcodes,
      ];

      if ($saved_language) {
        $form['default_language']['#default_value'] = $saved_language;
      }

    }

    return $form;
  }

  /**
   * {@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];
    }

    $langcode = $form_state->getValue('default_language');
    if ($langcode) {
      $this->entity->set('langcode', $langcode);
    }

    $status = parent::save($form, $form_state);
    $entity = $this->entity;
    if ($status == SAVED_UPDATED) {
      $this->messenger()
        ->addMessage($this->t('The fragment %feed has been updated.', ['%feed' => $entity->toLink()->toString()]));
    }
    else {
      $this->messenger()
        ->addMessage($this->t('The fragment %feed has been added.', ['%feed' => $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(
        'nodehive_core_space_dashboard.content_fragments',
        [
          "nodehive_space" => $space_id,
        ],
      );
    }
    else {
      $form_state->setRedirect(
        'entity.nodehive_fragment.collection',
        [
          "nodehive_fragment" => $this->entity->id(),
        ],
      );
    }
    return $status;
  }

}
