<?php

namespace Drupal\translatable_config_pages;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\translatable_config_pages\Entity\TranslatableConfigPages;

/**
 * Class used as loader for ConfigPages.
 *
 * @package Drupal\translatable_config_pages
 */
class TranslatableConfigPagesManager implements TranslatableConfigPagesManagerInterface {


  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

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

  /**
   * {@inheritdoc}
   */
  public function loadConfig(string $bundle, LanguageInterface $language = NULL): ?TranslatableConfigPages {
    $entity = NULL;

    try {
      $entity = $this->getEntityByBundle($bundle);
    }
    catch (InvalidPluginDefinitionException | PluginNotFoundException $e) {
      // Do nothing.
    }

    if (!$entity) {
      return NULL;
    }

    if (is_null($language)) {
      return $entity;
    }

    if ($entity->hasTranslation($language->getId())) {
      return $entity->getTranslation($language->getId());
    }

    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function loadConfigFieldValue(string $bundle, string $field, LanguageInterface $language = NULL): mixed {
    $entity = $this->loadConfig($bundle, $language);

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

    return NULL;
  }

  /**
   * Get entity by bundle.
   *
   * @param string $bundle
   *   The bundle of the content entity.
   *
   * @return false|mixed
   *   The entity or false.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getEntityByBundle(string $bundle): mixed {
    $configPages = $this->entityTypeManager->getStorage('translatable_config_pages')
      ->loadByProperties(['bundle' => $bundle]);

    if (is_array($configPages) && count($configPages) >= 1) {
      return reset($configPages);
    }

    return FALSE;
  }

}
