<?php

/**
 * @file
 * Provides a space dashboard functionality.
 */

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\node\NodeForm;
use Drupal\node\NodeInterface;

/**
 * Implements hook_entity_base_field_info().
 */
function nodehive_core_space_dashboard_entity_base_field_info(EntityTypeInterface $entity_type): array {
  $fields = [];

  if ($entity_type->id() === 'nodehive_space') {
    $fields['nodehive_space_views'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Dashboard Content Views'))
      ->setDescription(t('Views to be used in the dashboard content block.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'view')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', [
        'type'     => 'options_buttons',
        'weight'   => -2,
        'settings' => [],
      ])
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}

/**
 * Implements hook_form_alter().
 */
function nodehive_core_space_dashboard_form_alter(&$form, FormStateInterface $form_state, string $form_id) {
  // Add custom submit handler.
  if (in_array($form_id, ["nodehive_space_add_form", "nodehive_space_edit_form"])) {
    array_unshift($form['actions']['submit']['#submit'], "_nodehive_core_space_dashboard_nodehive_space_form_submit");
  }

  $query = \Drupal::request()->query->get("space");
  if (!$query) {
    return;
  }

  $form_object = $form_state->getFormObject();
  if (!$form_object instanceof NodeForm) {
    return;
  }

  $entity = $form_object->getEntity();
  if ($entity->isNew() == FALSE || !$entity instanceof NodeInterface) {
    return;
  }

  $space = \Drupal::entityTypeManager()->getStorage("nodehive_space")->load($query);
  if (!$space) {
    return;
  }

  if (isset($form["nodehive"])) {
    $form['nodehive']['select_space']['#default_value'] = [$space->id()];
  }
  elseif (isset($form["nodehive_space_information"])) {
    $form['nodehive_space_information'][0]['widget']['#default_value'] = [$space->id()];
  }

}

/**
 * Custom submit handler for nodehive_space forms.
 *
 * @param array $form
 *   Form object.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current form state.
 */
function _nodehive_core_space_dashboard_nodehive_space_form_submit(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $nodehive_space_content_view_key = NULL;

  foreach ($values['nodehive_space_views'] as $key => $value) {
    if ($value['target_id'] == "nodehive_space_content") {
      $nodehive_space_content_view_key = $key;
    }
  }

  if (is_null($nodehive_space_content_view_key)) {
    $form_state->setValue("nodehive_space_views", [["target_id" => "nodehive_space_content"]]);
    return;
  }

  unset($values["nodehive_space_views"][$nodehive_space_content_view_key]);
  $values["nodehive_space_views"][] = ["target_id" => "nodehive_space_content"];
  $form_state->setValue("nodehive_space_views", $values["nodehive_space_views"]);
}
