<?php

namespace Drupal\materio_sapi\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MaterioSapiSearchForm.
 */
class MaterioSapiSearchForm extends FormBase {


  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'materio_sapi_search_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $lang =  \Drupal::languageManager()->getCurrentLanguage()->getId();

    $keys = \Drupal::request()->get('keys');
    $term = \Drupal::request()->get('term');
    $filters = \Drupal::request()->get('filters');

    $form['#cache'] = array(
      'contexts' => array(
        'url.query_args:keys',
        'url.query_args:term',
        'url.query_args:filters',
      ),
    );

    $form['search'] = [
      '#type' => 'textfield',
      // '#title' => $this->t('Search'),
      '#maxlength' => 150,
      '#size' => 25,
      '#weight' => '0',
      '#attributes' => [
        "placeholder" => $this->t('Search'),
        // "@keyup" => "keyup",
        // "@keyup.enter" => "submit",
        "v-model" => "typed",
        "v-focus" => "",
        // "v-on:select" => "typed",
      ],
      '#autocomplete_route_name' => 'materio_sapi.search_autocomplete',

    ];
    $form['searchautocomplete'] = [
      '#type' => 'hidden',
      '#attributes' => [
        "v-model" => "autocomplete"
      ],
    ];

    // $filters_array = [];
    $filters_classes = [];
    if($filters){
      $filters_array = explode(',',$filters);
      $filters_classes[] = 'open';
    }
    $form['filters'] = [
      '#type' => 'fieldset',
      '#title' => t('filters'),
      '#legend_attributes' => [
        "class" => ["test-attribute"],
        '@click.prevent' => "onClickFilters",
      ],
      '#attributes' => [
        "class" => $filters_classes
      ]
    ];

    // $form['filters']['switch'] = [
    //   '#type' => "label",
    //
    // ]
    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "assisted_research")
          ->accessCheck(TRUE)
          ->sort('field_weight', 'ASC');
    $tids = $query->execute();
    $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);

    foreach ($terms as $tid => $term) {
      if($term->hasTranslation($lang)){
        $term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $lang);
      }
      $options = array($term->getName());
      $childs = $term->get('field_terms')->getValue();
      $selected = null;
      foreach ($childs as $child) {
        $child_term = \Drupal\taxonomy\Entity\Term::load($child['target_id']);
        if($child_term->hasTranslation($lang)){
          $child_term = \Drupal::service('entity.repository')->getTranslationFromContext($child_term, $lang);
        }
        $options[$child_term->id()] = $child_term->getName();
        if (isset($filters_array) && in_array($child_term->id(), $filters_array)) {
          $selected = $child_term->id();
        }
      }
      $form['filters']['filter-'.$tid] = array(
        '#type' => 'select',
        // '#title' => $term->getName(),
        // '#multiple' => true,
        '#options' => $options,
        '#value' => $selected
      );
    }


    $form['submit'] = array(
        '#type'   => 'button',
        // '#src'    => '',//drupal_get_path('module', 'materio_search_api') . '/images/search.png',
        '#value'  => t('Search'),
        // '#prefix' => '<div class="search-btn-wrapper">',
        // '#suffix'=> '</div>',
        '#attributes' => [
          'title' => t('Search'),
          '@click.prevent' => "submit",
        ]
      );
    return $form;
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

  }

}
