<?php

/**
 * @file
 * Provides a rendered preview of a paragraphs item on an entity form.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Implements hook_theme().
 */
function paragraphs_previewer_theme() {
  return [
    'paragraphs_previewer_modal_content' => [
      'variables' => array('preview_url' => NULL),
      'file' => 'paragraphs_previewer.theme.inc',
    ],
  ];
}

/**
 * Implements hook_preprocess_html().
 */
function paragraphs_previewer_preprocess_html__paragraphs_previewer(&$variables) {
  unset($variables['page_top']);
  unset($variables['page_bottom']);
  if (isset($variables['html_attributes'])) {
    $variables['html_attributes']->addClass('paragraphs-previewer-html');
  }

  $variables['attributes']['class'][] = 'paragraphs-previewer';
}

/**
 * Implements hook_preprocess_page().
 */
function paragraphs_previewer_preprocess_page__paragraphs_previewer(&$variables) {
  if (!empty($variables['page'])) {
    $page_keys = Element::children($variables['page']);
    foreach ($page_keys as $page_key) {
      if ($page_key != 'content') {
        unset($variables['page'][$page_key]);
      }
      elseif ($content_keys = Element::children($variables['page'][$page_key])) {
        foreach ($content_keys as $content_key) {
          if (isset($variables['page'][$page_key][$content_key]['#base_plugin_id']) &&
              $variables['page'][$page_key][$content_key]['#base_plugin_id'] != 'system_main_block') {
            unset($variables['page'][$page_key][$content_key]);
          }
        }
      }
    }
  }
}

/**
 * Implements hook_form_entity_form_display_edit_form_alter().
 */
function paragraphs_previewer_form_entity_form_display_edit_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if (empty($form['fields'])) {
    return;
  }

  $field_names = Element::children($form['fields']);
  if (empty($field_names)) {
    return;
  }

  // Remove DEPRECATED plugin id from the widget type options list.
  $deprecated_id = 'paragraphs_previwer';
  foreach ($field_names as $field_name) {
    if (!empty($form['fields'][$field_name]['plugin']['type']['#options'][$deprecated_id])) {
      unset($form['fields'][$field_name]['plugin']['type']['#options'][$deprecated_id]);
    }
  }
}
