<?php

namespace Drupal\straker_translate\Element;

use Drupal\Core\Render\Element\RenderElement;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\straker_translate\StrakerTranslate;

/**
 * Provides a Straker Translate target status element.
 *
 * @RenderElement("straker_translate_target_status")
 */
class StrakerTranslateTargetStatus extends RenderElement {

  use StrakerTranslateTargetTrait;

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#pre_render' => [
        [$this, 'preRender'],
      ],
      '#theme' => 'straker_translate_target_status',
      '#attached' => [
        'library' => [
          'straker_translate/straker_translate',
          'straker_translate/straker_translate.target_actions',
        ],
      ],
      '#cache' => [
        'max-age' => 0,
      ],
    ];
  }

  /**
   * Calculates the url and status title and adds them to the render array.
   *
   * @param array $element
   *   The element as a render array.
   *
   * @return array
   *   The element as a render array.
   */
  public function preRender(array $element) {
    $isSourceLanguage = $element['#entity']->language()->getId() === $element['#language'];
    if ($isSourceLanguage) {
      return [];
    }
    if (NULL === ConfigurableLanguage::load($element['#language'])) {
      return [];
    }
    $element['#url'] = $this->getTargetActionUrl($element['#entity'], $element['#status'], $element['#language']);
    $hasTranslation = $element['#entity']->hasTranslation($element['#language']);
    $element['#new_window'] = !($hasTranslation && $element['#status'] == StrakerTranslate::STATUS_REQUEST) && in_array($element['#status'], [StrakerTranslate::STATUS_CURRENT, StrakerTranslate::STATUS_INTERMEDIATE, StrakerTranslate::STATUS_EDITED]);
    $element['#status_text'] = $this->getTargetStatusText($element['#status'], $element['#language'], $hasTranslation);
    $element['#actions'] = $this->getSecondaryTargetActionUrls($element['#entity'], $element['#status'], $element['#language']);
    return $element;
  }

}
