<?php

declare(strict_types=1);

namespace Drupal\sobki_background_image\Plugin\UiPatterns\Source;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\sobki_background_image\Form\SettingsForm;
use Drupal\sobki_background_image\Service\BackgroundImageStyleInterface;
use Drupal\ui_patterns\Attribute\Source;
use Drupal\ui_patterns\AttributesTrait;
use Drupal\ui_patterns\SourcePluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the source.
 */
#[Source(
  id: 'sobki_background_image_attributes',
  label: new TranslatableMarkup('Background image attributes'),
  description: new TranslatableMarkup('Allows to set a background image.'),
  prop_types: ['attributes']
)]
class BackgroundImageAttributes extends SourcePluginBase {

  use AttributesTrait;

  /**
   * The background image style service.
   *
   * @var \Drupal\sobki_background_image\Service\BackgroundImageStyleInterface
   */
  protected BackgroundImageStyleInterface $backgroundImageStyle;

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected ConfigFactoryInterface $configFactory;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->backgroundImageStyle = $container->get('sobki_background_image.background_image_style');
    $instance->configFactory = $container->get('config.factory');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getPropValue(): array {
    $settings = $this->getSetting('sobki_background_image');
    if (!\is_array($settings)) {
      return [];
    }

    $style = $this->backgroundImageStyle->getBackgroundImageStyle($settings);
    if (empty($style)) {
      return [];
    }

    return [
      'style' => $style,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state): array {
    $form = parent::settingsForm($form, $form_state);
    $config = $this->configFactory->get(SettingsForm::CONFIG_NAME);
    $mapping = $config->get('media_bundle_mapping');
    if (!\is_array($mapping)) {
      return $form;
    }

    $allowedBundles = \array_keys($mapping);
    if (empty($allowedBundles)) {
      return $form;
    }

    $settings = $this->getSetting('sobki_background_image');
    $form['sobki_background_image'] = [
      '#type' => 'sobki_background_image',
      '#title' => $this->t('Background image'),
      '#media_bundles' => $allowedBundles,
      '#default_value' => $settings,
      '#tree' => TRUE,
    ];

    return $form;
  }

}
