<?php

namespace Drupal\translatable_config_pages\Commands;

use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\translatable_config_pages\TranslatableConfigPagesManagerInterface;
use Drush\Commands\DrushCommands;

/**
 * A Drush commandfile.
 *
 * In addition to this file, you need a drush.services.yml
 * in root of your module, and a composer.json file that provides the name
 * of the services file to use.
 *
 * See these files for an example of injecting Drupal services:
 *   - http://cgit.drupalcode.org/devel/tree/src/Commands/DevelCommands.php
 *   - http://cgit.drupalcode.org/devel/tree/drush.services.yml
 */
class TranslatableConfigPagesCommands extends DrushCommands {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected LanguageManagerInterface $languageManager;

  /**
   * The translatable config page manager.
   *
   * @var \Drupal\translatable_config_pages\TranslatableConfigPagesManagerInterface
   */
  protected TranslatableConfigPagesManagerInterface $translatableConfigPagesManager;

  /**
   * The constructor.
   *
   * @param \Drupal\translatable_config_pages\TranslatableConfigPagesManagerInterface $translatableConfigPagesManager
   *   The translatable config page manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language manager.
   */
  public function __construct(
    TranslatableConfigPagesManagerInterface $translatableConfigPagesManager,
    LanguageManagerInterface $languageManager
  ) {
    parent::__construct();
    $this->translatableConfigPagesManager = $translatableConfigPagesManager;
    $this->languageManager = $languageManager;
  }

  /**
   * Get config field value by bundle and langcode.
   *
   * @param string $bundle
   *   The bundle.
   * @param string $field
   *   The field.
   * @param string $langcode
   *   The langcode.
   *
   * @usage translatable_config_pages-getConfigFieldValue foo
   *   Pass the bundle, the field and optionally the langcode.
   *
   * @command translatable_config_pages:getConfigFieldValue
   * @aliases tcp-gc-fv
   */
  public function getTranslatableConfigPageFieldValue(string $bundle, string $field, string $langcode = '') {
    if (empty($langcode)) {
      $entity = $this->translatableConfigPagesManager->loadConfig($bundle);
    }
    else {
      $language = $this->languageManager->getLanguage($langcode);
      $entity = $this->translatableConfigPagesManager->loadConfig($bundle, $language);
    }

    if ($entity && $entity->hasField($field)) {
      return $entity->get($field)->getString();
    }

    $this->logger()->error('The bundle or field does not exist');
  }

}
