<?php

namespace Drupal\straker_translate\EventSubscriber;

use Drupal\Core\Config\ConfigCrudEvent;
use Drupal\Core\Config\ConfigEvents;
use Drupal\Core\Field\FieldConfigInterface;
use Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Core\Installer\InstallerKernel;

/**
 * Updates Straker Translate config if a field is deleted.
 */
class StrakerTranslateFieldDeletedConfigSubscriber implements EventSubscriberInterface {

  /**
   * The Straker Translate configuration service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface
   */
  protected $straker_translateConfiguration;

  /**
   * Constructs a StrakerTranslateFieldDeletedConfigSubscriber.
   *
   * @param \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface $straker_translate_configuration
   *   The Straker Translate configuration service.
   */
  public function __construct(StrakerTranslateConfigurationServiceInterface $straker_translate_configuration) {
    $this->straker_translateConfiguration = $straker_translate_configuration;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      ConfigEvents::DELETE => 'onConfigDelete',
    ];
  }

  /**
   * Updates the Straker Translate configuration when a field is deleted.
   *
   * @param \Drupal\Core\Config\ConfigCrudEvent $event
   *   The configuration event.
   */
  public function onConfigDelete(ConfigCrudEvent $event) {
    if (!InstallerKernel::installationAttempted()) {
      $config = $event->getConfig();
      if ($config instanceof FieldConfigInterface) {
        $field_name = $config->getName();
        $entity_type_id = $config->getTargetEntityTypeId();
        $bundle = $config->getTargetBundle();

        $this->straker_translateConfiguration->setFieldStrakerTranslateEnabled($entity_type_id, $bundle, $field_name, FALSE);
      }
    }

  }

}
