<?php

namespace Drupal\style_selector\Plugin\Field\FieldType;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\options\Plugin\Field\FieldType\ListStringItem;

/**
 * Plugin implementation of the 'style_selector_css_color' field type.
 *
 * @FieldType(
 *   id = "style_selector_css_color",
 *   label = @Translation("Color list"),
 *   description = @Translation("Store and select CSS colors from a list of predefined values."),
 *   category = "style_selector",
 *   default_widget = "style_selector_compact_widget",
 *   default_formatter = "style_selector_css_color_formatter",
 * )
 */
class CssColorItem extends ListStringItem {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  protected function allowedValuesDescription() {
    $description =  '<p>' . $this->t('Name will be used in displayed values and edit forms. Value must be a valid, supported CSS color format.');
    $description .= '<br/>' . $this->t('Hex color values must be prefixed with #, and will be stored in RGB format.');
    $description .= '</p><p><b>' . $this->t('Examples:');
    $description .= '</b><br/>' . $this->t('White ⇒ #fff');
    $description .= '<br/>' . $this->t('Current Text Color ⇒ currentColor');
    $description .= '<br/>' . $this->t('Semi-transparent Black ⇒ rgba(0,0,0,0.5)');
    $description .= '</p>';
    return $description;
  }

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $element = parent::storageSettingsForm($form, $form_state, $has_data);

    // Revert to 'textfields' for key values, rather than 'machine_name' which
    // attempts to auto-generate the value.
    foreach (Element::children($element['allowed_values']['table']) as $delta => $row) {
      $element['allowed_values']['table'][$delta]['item']['key']['#type'] = 'textfield';
      $element['allowed_values']['table'][$delta]['item']['key']['#machine_name'] = [];
      $element['allowed_values']['table'][$delta]['item']['key']['#process'] = [];
      $element['allowed_values']['table'][$delta]['item']['key']['#element_validate'] = [];
    }

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected static function validateAllowedValue($option) {
    parent::validateAllowedValue($option);
    if (!\Drupal::service('style_selector.css_color')->getFormSafeColorValue($option)) {
      return t('Value @opt is not a valid CSS color.', [
        '@opt' => $option,
      ]);
    }
  }

  /**
   * {@inheritdoc}
   */
  protected static function castAllowedValue($value) {
    // Convert hex values are converted to rgb.
    return (string) \Drupal::service('style_selector.css_color')->getFormSafeColorValue($value);
  }

}
