<?php

namespace Drupal\straker_translate;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\language\Entity\ConfigurableLanguage;

/**
 *
 */
class LanguageLocaleMapper implements LanguageLocaleMapperInterface {

  /**
   * The Entity Type Manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new StrakerTranslateConfigTranslationService object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritDoc}
   */
  public function getConfigurableLanguageForLocale($locale) {
    $drupal_language = NULL;
    $id = $this->entityTypeManager->getStorage('configurable_language')->getQuery()
      ->accessCheck(FALSE)
      ->condition('third_party_settings.straker_translate.locale', $locale)
      ->execute();
    if (!empty($id)) {
      $drupal_language = ConfigurableLanguage::load(reset($id));
    }
    else {
      $drupal_language = ConfigurableLanguage::load(StrakerTranslateLocale::convertStrakerTranslate2Drupal($locale));
    }
    return $drupal_language;
  }

  /**
   * {@inheritDoc}
   */
  public function getLocaleForLangcode($langcode) {
    /** @var \Drupal\language\ConfigurableLanguageInterface $config_language */
    $config_language = ConfigurableLanguage::load($langcode);
    $locale = NULL;
    if ($config_language) {
      $locale = $config_language->getThirdPartySetting('straker_translate', 'locale', StrakerTranslateLocale::convertDrupal2StrakerTranslate($langcode));
    }
    return $locale;
  }

}
