<?php

namespace Drupal\castorcito_date\Plugin\CastorcitoComponentField;

use Drupal\castorcito\ConfigurableComponentFieldBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Form\FormStateInterface;

/**
 * Date configuration.
 *
 * @CastorcitoComponentField(
 *   id = "date",
 *   label = @Translation("Date"),
 *   description = @Translation("Configuration for the date field.")
 * )
 */
class Date extends ConfigurableComponentFieldBase {

  /**
   * {@inheritdoc}
   */
  public function defaultModel() {
    return [
      'value' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'date_type' => 'datetime',
      'display' => [
        'format_type' => 'medium',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['date_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Date type'),
      '#default_value' => $this->configuration['date_type'],
      '#required' => TRUE,
      '#options' => [
        'datetime' => $this->t('Date and time'),
        'date' => $this->t('Date only'),
      ],
    ];

    $form['display'] = [
      '#type' => 'details',
      '#title' => $this->t('Display'),
      '#open' => TRUE,
    ];

    $time = new DrupalDateTime();
    $format_types = \Drupal::entityTypeManager()->getStorage('date_format')->loadMultiple();
    $date_formatter = \Drupal::service('date.formatter');
    $options = [];
    foreach ($format_types as $type => $type_info) {
      $format = $date_formatter->format($time->getTimestamp(), $type);
      $options[$type] = $type_info->label() . ' (' . $format . ')';
    }

    $form['display']['format_type'] = [
      '#title' => $this->t('Date format'),
      '#type' => 'select',
      '#default_value' => $this->configuration['display']['format_type'] ?? NULL,
      '#description' => $this->t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."),
      '#options' => $options,
    ];

    return $form;
  }

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

}
