<?php

namespace Drupal\pagedesigner_block\Plugin\Condition;

use Drupal\Core\Condition\ConditionInterface;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Condition to hide items in pagedesigner edit mode.
 *
 * @Condition(
 *   id = "pagedesigner_condition",
 *   label = @Translation("Pagedesigner condition"),
 * )
 */
class PagedesignerCondition extends ConditionPluginBase implements ConditionInterface, ContainerFactoryPluginInterface {

  /**
   * The configuration key.
   *
   * @var string
   */
  protected $configKey = 'pagedesigner_condition';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
          $configuration,
          $plugin_id,
          $plugin_definition
      );
  }

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    if (empty($this->configuration) || !isset($this->configuration[$this->configKey])) {
      return TRUE;
    }
    if (\Drupal::service('pagedesigner.service')->isEditMode() && $this->configuration[$this->configKey]) {
      return FALSE;
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    return $this->t(
          'Hide the block in pagedesigner mode.'
      );
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form[$this->configKey] = [
      '#type' => 'checkbox',
      '#title' => $this->t("Hide in pagedesigner"),
      '#description' => $this->t("Hide this block in pagedesigner."),
    ];
    $form[$this->configKey]['#default_value'] = $this->configuration[$this->configKey];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration[$this->configKey] = $form_state->getValue($this->configKey);
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [$this->configKey => ''] + parent::defaultConfiguration();
  }

}
