<?php

namespace Drupal\straker_translate\Controller;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 *
 */
class StrakerTranslateSupportedLocalesController extends StrakerTranslateControllerBase {

  /**
   *
   */
  public function content() {
    $locales = $this->straker_translate->getLocalesInfo();

    $build = [];
    $build['#attached']['library'][] = 'straker_translate/straker_translate.locales_listing';

    $build['filters'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['table-filter', 'js-show'],
      ],
    ];

    $build['filters']['text'] = [
      '#type' => 'search',
      '#title' => $this->t('Filter'),
      '#title_display' => 'invisible',
      '#size' => 60,
      '#placeholder' => $this->t('Filter per language code, Title'),
      '#attributes' => [
        'class' => ['locales-filter-text'],
        'data-table' => '.locales-listing-table',
        'autocomplete' => 'off',
        'title' => $this->t('Enter a code or name of any language, locale, or country to filter by.'),
      ],
    ];

    $build['locales'] = [
      '#type' => 'table',
      '#header' => [
        'id' => $this->t('id'),
        'language_code' => $this->t('Language Code'),
        'title' => $this->t('Title'),
      ],
      '#rows' => $locales,
      '#attributes' => ['class' => ['locales-listing-table']],
    ];

    return $build;
  }

  /**
   * Callback for the autocomplete of supported locales.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing the autocomplete suggestions.
   */
  public function autocomplete(Request $request) {
    // Get autocomplete query.
    $q = $request->query->get('q') ?: '';
    if ($q == '') {
      return new JsonResponse([]);
    }

    $locales = $this->straker_translate->getLocalesInfo();
    $matches = [];
    foreach ($locales as $locale => $locale_info) {
      $fieldsToSearch = [
        'id' => $this->t('id'),
        'language_code' => $this->t('Language Code'),
        'title' => $this->t('Title'),
      ];
      foreach ($fieldsToSearch as $field => $fieldDescription) {
        if (stripos($locale_info[$field], $q) !== FALSE) {
          $matches[] = [
            'value' => $locale,
            'label' => new FormattableMarkup('[%value] - @id', [
              '%value' => Html::escape($locale_info[$field]),
              '@id' => Html::escape($locale_info['id']),
            ]),
          ];
          continue 2;
        }
      }
    }
    return new JsonResponse($matches);
  }

}
