<?php

namespace Drupal\materio_samples\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\workflow\Entity\WorkflowManager;

/**
 * Plugin implementation of the 'materio_samples_default_widget' widget.
 *
 * @FieldWidget(
 *   id = "materio_samples_default_widget",
 *   module = "materio_samples",
 *   label = @Translation("Samples"),
 *   field_types = {
 *     "materio_samples_field"
 *   }
 * )
 */
class SamplesDefaultWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
    // construct "manually" the list of items
    $vid = $this->fieldDefinition->getSetting('vid');
    $query = \Drupal::entityQuery('taxonomy_term')
        ->sort('weight', 'DESC')
        // ->sort('tid', 'DESC')
        ->condition('vid', $vid);
    $tids = $query->execute();
    $terms = Term::loadMultiple($tids);

    // define the cardinality, this will remove the add_more btn
    $this->fieldDefinition->getFieldStorageDefinition()->setCardinality(count($terms));

    $locations = [];
    foreach ($items as $delta => $item) {
      $locations[$item->target_id] = $item->location;
    }

    $delta = 0;
    foreach ($terms as $term) {
      // remove masqué
      $sid = WorkflowManager::getCurrentStateId($term, 'field_workflow');
      if($sid == 'workflow_hidden') continue;
      $location = isset($locations[$term->id()]) ? $locations[$term->id()] : '';
      $value = array(
        'location' => $location,
        'target_id'=> $term->id()
      );
      $items->set($delta, $value);
      $delta ++;
    }

    // then call the normal form
    $elements = parent::form($items, $form, $form_state, $get_delta);
    // dsm($elements);

    // Arrange the form object to remove draggable table stuff
    $elements['widget']['#cardinality_multiple'] = FALSE;
    for ($i=0; $i <= $delta ; $i++) {
      if(isset($elements['widget'][$i]['_weight'])){
        $elements['widget'][$i]['_weight']['#type'] = 'hidden';
      }
    }

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

    // get default values
    $target_id = isset($items[$delta]->target_id) ? $items[$delta]->target_id : 0;
    $location = isset($items[$delta]->location) ? $items[$delta]->location : '';
    // dsm($target_id);

    // return nothing if target_id is null
    if(!$target_id) return;

    $term = Term::load($target_id);

    // translate the term
    $term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);

    // dsm($element);
    // $element['#attributes'] = array('class' => array('container-inline'));
    // $element['container'] = [
    //   '#type' => 'container',
    //   '#field_prefix' => '<div class="container-inline">',
    //   '#field_suffix' => '</div>',
    // ];
    $element['target_id'] = [
      '#type' => 'hidden',
      '#default_value' => $target_id,
    ];
    $element['location'] = [
      '#title' => $term->getName(),
      '#type' => 'textfield',
      '#default_value' => $location,
      '#size' => 10,
      '#maxlength' => 15,
      '#attributes' => ['class' => ['container-inline']],
    ];
    // return ['value' => $element];
    return $element;
  }

  public function validate($element, FormStateInterface $form_state) {
    // dsm($element);
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // foreach ($values as $key => $value) {
    //   $values[$key]['value']['target_id'] = (int)$values[$key]['value']['target_id'];
    // }
    dsm($values);
    return $values;
  }
}
