<?php

/**
 * @file
 * Primary module hooks for nodehive_visualeditor module.
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\nodehive_visualeditor\Form\NodeEditForm;

/**
 * Implements hook_theme().
 */
function nodehive_visualeditor_theme()
{
  return [
    'nodehive_visualeditor' => [
      'variables' => [
        'url' => NULL,
        'recent_edit_form' => NULL,
        'base_url' => NULL,
        'frontend_login_url' => NULL,
        'selected_space' => [],
        'spaces' => NULL,
        'selected_space_id' => NULL,
        'development_mode' => FALSE,
        'edit_form' => [],
        'tabs' => NULL,
        'jwt_token' => NULL,
      ],
    ],
    'page__visualeditor' => [
      'variables' => [
        'content' => NULL
      ],
    ],
    'space__selector' => [
      'variables' => [
        'spaces' => NULL,
        'selected_space_id' => NULL,
      ],
    ],
    'composable__node_edit_form' => [
      'render element' => 'form',
      'base hook' => 'node_edit_form',
    ],
    'off_canvas' => [
      'variables' => [
        'menu' => NULL,
        'form' => NULL,
      ],
    ],
  ];
}

function nodehive_visualeditor_theme_suggestions_node_edit_form_alter(array &$suggestions, array $variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'nodehive_visualeditor.node_controller.edit') {
    $suggestions[] = 'composable__' . $variables['theme_hook_original'];
  }

  return $suggestions;
}

function nodehive_visualeditor_theme_suggestions_page_alter(array &$suggestions, array $variables)
{
  // Check if the current path is 'visualeditor'.
  if (\Drupal::service('path.current')->getPath() === '/visualeditor') {
    // Add a new template suggestion for paths that match 'visualeditor'.
    $suggestions[] = 'page__visualeditor';
  }

  $current_route_name = \Drupal::routeMatch()->getRouteName();
  if ($current_route_name === 'nodehive_visualeditor.visual_editor_single') {
    $suggestions[] = 'page__visualeditor';
  }

}

/**
 * Implements hook_page_attachments().
 */
function nodehive_visualeditor_page_attachments(array &$attachments)
{
  $attachments['#attached']['library'][] = 'nodehive_visualeditor/nodehive_visualeditor';
}

function nodehive_visualeditor_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  $request = Drupal::request();
  if (!$request->isXmlHttpRequest()) {
    return;
  } else {

    //\Drupal::messenger()->addMessage("Altering form with ID: $form_id");
    // Check if the form ID matches the specific pattern.
    if (preg_match('/^nodehive_fragment_.*_edit_form$/', $form_id)) {
      $form['actions']['submit']['#ajax'] = [
        'callback' => 'nodehive_visualeditor_reload_iframe',
        'disable-refocus' => TRUE,
        'progress' => 'none',
      ];
    }

    // Apply alterations for all menu forms.
    if (strpos($form_id, 'menu_edit_form') !== FALSE) {
      $form['actions']['submit']['#ajax'] = [
        'callback' => 'nodehive_visualeditor_reload_iframe',
        'disable-refocus' => TRUE,
        'progress' => 'none',
      ];
    }



  }
}
/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodehive_visualeditor_form_paragraph_form_alter(&$form, FormStateInterface $form_state)
{
  $request = Drupal::request();

  if (!$request->isXmlHttpRequest()) {
    return;
  }

  $form['actions']['submit']['#ajax'] = [
    'callback' => 'nodehive_visualeditor_reload_iframe',
    'disable-refocus' => TRUE,
    'progress' => 'none',
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodehive_visualeditor_form_fragment_form_alter(&$form, FormStateInterface $form_state)
{
  $request = Drupal::request();

  if (!$request->isXmlHttpRequest()) {
    return;
  }

  $form['actions']['submit']['#ajax'] = [
    'callback' => 'nodehive_visualeditor_reload_iframe',
    'disable-refocus' => TRUE,
    'progress' => 'none',
  ];
}


/**
 * Ajax callback to reload iframe.
 *
 * @param array $form
 *   Current form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current form state.
 */
function nodehive_visualeditor_reload_iframe(array &$form, FormStateInterface $form_state)
{
  $response = new AjaxResponse();
  $response->addCommand(new InvokeCommand(NULL, 'iframePreviewReload'));
  return $response;
}

function nodehive_visualeditor_submit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

/**
 * Implements hook_entity_type_build().
 */
function nodehive_visualeditor_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('composable', NodeEditForm::class);
}
