<?php

namespace Drupal\uw_cfg_common\CustomBlocks;

use Drupal\core_event_dispatcher\Event\Form\FormAlterEvent;
use Drupal\preprocess_event_dispatcher\Event\BlockPreprocessEvent;

/**
 * Class UwCblBase.
 */
class UwCblBase {

  /**
   * Check that we are on a layout builder add/edit form and that we are on
   * a specified block.
   *
   * @param \Drupal\core_event_dispatcher\Event\Form\FormAlterEvent $event
   *   The event.
   * @param string $block_name
   *   The human readable name of the block.
   * @return boolean
   */
  public function checkLayoutBuilder(FormAlterEvent $event, string $block_name): bool {

    // Get the form from the event.
    $form = &$event->getForm();

    // Get the form_id from the form object.
    $form_id = $form['#form_id'];

    // Form ids to check for.
    $form_ids = ['layout_builder_update_block', 'layout_builder_add_block'];

    // If we are not in a layout builder, exit the function.
    if (!in_array($form_id, $form_ids)) {
      return FALSE;
    }

    // Check for correct block name.
    if (isset($form['settings']['admin_label']['#plain_text']) && $form['settings']['admin_label']['#plain_text'] == $block_name) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Check if we have the correct block id to preprocess.
   *
   * @param Drupal\hook_event_dispatcher\Event\Preprocess\BlockPreprocessEvent $event
   *   The event.
   * @param string $block_id
   *   The id of the block to check.
   * @return boolean
   */
  public function checkPreprocessBlock(BlockPreprocessEvent $event, string $block_id): bool {

    // Get the variables from the event.
    $variables = $event->getVariables();

    // If the plugin does not much the block id, return negative.
    if ($variables->get('derivative_plugin_id') !== $block_id) {
      return FALSE;
    }

    return TRUE;
  }
}