<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFormComponent\Field;

use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityInterface;
use Drupal\straker_translate\StrakerTranslate;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentFieldBase;

/**
 * Defines a Straker Translate form-field plugin for an entity ID.
 *
 * @StrakerTranslateFormComponentField(
 *   id = "translations",
 *   title = @Translation("Translations"),
 *   weight = 400,
 *   form_ids = {
 *     "straker_translate_management",
 *     "straker_translate_entity_management",
 *     "straker_translate_job_content_entities_management"
 *   }
 * )
 */
class Translations extends StrakerTranslateFormComponentFieldBase {

  use DependencySerializationTrait;

  /**
   * {@inheritdoc}
   */
  public function getData(EntityInterface $entity) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $statuses = $this->translationService->getTargetStatuses($entity);
    /** @var \Drupal\straker_translate\StrakerTranslateProfileInterface $profile */
    $profile = $this->straker_translateConfiguration->getEntityProfile($entity);
    array_walk($statuses, function (&$status, $langcode) use ($profile) {
      if ($profile !== NULL && $profile->hasDisabledTarget($langcode)) {
        $status = StrakerTranslate::STATUS_DISABLED;
      }
    });
    $languages = $this->straker_translateConfiguration->getEnabledLanguages();
    foreach ($languages as $langcode => $language) {
      if ($profile !== NULL && $profile->hasDisabledTarget($langcode)) {
        $statuses[$langcode] = StrakerTranslate::STATUS_DISABLED;
      }
    }
    // Get the source language to exclude it from target languages
    $source_langcode = $entity->language()->getId();

    // Build simple language name list
    $language_names = [];
    foreach ($languages as $langcode => $language) {
      // Skip the source language
      if ($langcode !== $source_langcode) {
        $language_names[] = '<div class="translation-language-item">' . $language->getName() . '</div>';
      }
    }

    // Return the language names with proper spacing
    return [
      'data' => [
        '#markup' => '<div class="translation-languages-wrapper">' . implode('', $language_names) . '</div>',
        '#attached' => [
          'library' => ['straker_translate/base'],
        ],
      ],
    ];
  }

}
