<?php

namespace Drupal\straker_translate\Element;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Render\Element\RenderElement;
use Drupal\Core\Url;
use Drupal\straker_translate\StrakerTranslate;

/**
 * Provides a Straker Translate source status element.
 *
 * @RenderElement("straker_translate_source_status")
 */
class StrakerTranslateSourceStatus extends RenderElement {

  use StrakerTranslateSourceTrait;

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#pre_render' => [
        [$this, 'preRender'],
      ],
      '#theme' => 'straker_translate_source_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) {
    if (isset($element['#entity'])) {
      $element['#url'] = $this->getSourceActionUrl($element['#entity'], $element['#status']);
      $element['#status_title'] = $this->getSourceStatusText($element['#entity'], $element['#status']);
      $element['#actions'] = $this->getSecondarySourceActionUrls($element['#entity'], $element['#status'], $element['#language']);
    }
    if (isset($element['#mapper'])) {
      $element['#url'] = $this->getSourceActionUrlForConfigMapper($element['#mapper']);
      $element['#status'] = $this->getSourceStatusForConfigMapper($element['#mapper']);
      $element['#status_title'] = $this->getSourceStatusTextForConfigMapper($element['#mapper'], $element['#status']);
      $element['#actions'] = $this->getSecondarySourceActionUrlsForConfigMapper($element['#mapper'], $element['#status'], $element['#language']);
    }
    elseif (isset($element['#ui_component'])) {
      $element['#url'] = $this->getSourceActionUrlForUI($element['#ui_component'], $element['#status']);
      $element['#status_title'] = $this->getSourceStatusTextForUI($element['#ui_component'], $element['#status']);
      $element['#actions'] = $this->getSecondarySourceActionUrlsForUI($element['#ui_component'], $element['#status']);
    }
    return $element;
  }

  /**
   * Get the source action url based on the source status.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity.
   * @param string $source_status
   *   The source status.
   *
   * @return \Drupal\Core\Url
   *   An url object.
   */
  protected function getSourceActionUrl(ContentEntityInterface &$entity, $source_status) {
    $url = NULL;
    if ($source_status == StrakerTranslate::STATUS_IMPORTING) {
      $url = Url::fromRoute('straker_translate.entity.confirm',
        ['doc_id' => \Drupal::service('straker_translate.content_translation')->getDocumentId($entity)],
        ['query' => $this->getDestinationWithQueryArray()]);
    }
    if (in_array($source_status, [StrakerTranslate::STATUS_READY, StrakerTranslate::STATUS_PROCESSING, StrakerTranslate::STATUS_ERROR])) {
      $url = Url::fromRoute('straker_translate.entity.check_upload',
        ['doc_id' => \Drupal::service('straker_translate.content_translation')->getDocumentId($entity)],
        ['query' => $this->getDestinationWithQueryArray()]);
    }
    if (in_array($source_status, [StrakerTranslate::STATUS_EDITED, StrakerTranslate::STATUS_UNTRACKED, StrakerTranslate::STATUS_ERROR, StrakerTranslate::STATUS_CANCELLED, StrakerTranslate::STATUS_ARCHIVED, StrakerTranslate::STATUS_DELETED])) {
      if ($doc_id = \Drupal::service('straker_translate.content_translation')->getDocumentId($entity)) {
        $url = Url::fromRoute('straker_translate.entity.update',
           [
             'entity_type' => $entity->getEntityTypeId(),
             'entity_id' => $entity->id(),
           ],
          ['query' => $this->getDestinationWithQueryArray()]);
      }
      else {
        $url = Url::fromRoute('straker_translate.entity.upload',
          [
            'entity_type' => $entity->getEntityTypeId(),
            'entity_id' => $entity->id(),
          ],
          ['query' => $this->getDestinationWithQueryArray()]);
      }
    }
    return $url;
  }

  /**
   *
   */
  protected function getSecondarySourceActionUrls(ContentEntityInterface &$entity, $source_status, $language) {
    $actions = [];
    if ($language != NULL) {
      $langcode = $language->getId();
      if ($entity->hasLinkTemplate('canonical') && $entity->hasTranslation($langcode)) {
        $actions[] = [
          'title' => $this->t('View'),
          'url' => $entity->getTranslation($langcode)->toUrl(),
          'new_window' => FALSE,
        ];
      }
    }
    $content_translation_service = \Drupal::service('straker_translate.content_translation');
    if ($source_status == StrakerTranslate::STATUS_IMPORTING) {
      $actions[] = [
        'title' => $this->t('Confirm document'),
        'url' => Url::fromRoute('straker_translate.entity.confirm',
          [
            'doc_id' => $content_translation_service->getDocumentId($entity),
          ],
          ['query' => $this->getDestinationWithQueryArray()]),
        'new_window' => FALSE,
      ];
    }
    if (in_array($source_status, [StrakerTranslate::STATUS_READY, StrakerTranslate::STATUS_PROCESSING, StrakerTranslate::STATUS_ERROR])) {
      $actions[] = [
        'title' => $this->t('Check upload status'),
        'url' => Url::fromRoute('straker_translate.entity.check_upload',
          [
            'doc_id' => $content_translation_service->getDocumentId($entity),
          ],
          ['query' => $this->getDestinationWithQueryArray()]),
        'new_window' => FALSE,
      ];
    }
    if (in_array($source_status, [
      StrakerTranslate::STATUS_EDITED,
      StrakerTranslate::STATUS_UNTRACKED,
      StrakerTranslate::STATUS_ERROR,
      StrakerTranslate::STATUS_CANCELLED,
      StrakerTranslate::STATUS_ARCHIVED,
      StrakerTranslate::STATUS_DELETED,
    ])) {
      if ($doc_id = $content_translation_service->getDocumentId($entity)) {
        $actions[] = [
          'title' => $this->t('Update document'),
          'url' => Url::fromRoute('straker_translate.entity.update',
            [
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
            ],
            ['query' => $this->getDestinationWithQueryArray()]),
          'new_window' => FALSE,
        ];
      }
      else {
        $actions[] = [
          'title' => $this->t('Upload document'),
          'url' => Url::fromRoute('straker_translate.entity.upload',
            [
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
            ],
            ['query' => $this->getDestinationWithQueryArray()]),
          'new_window' => FALSE,
        ];
      }
    }
    return $actions;
  }

  /**
   *
   */
  protected function getSecondarySourceActionUrlsForUI($component, $source_status) {
    $actions = [];
    $doc_id = \Drupal::service('straker_translate.interface_translation')->getDocumentId($component);
    if (in_array($source_status, [StrakerTranslate::STATUS_READY, StrakerTranslate::STATUS_PROCESSING, StrakerTranslate::STATUS_ERROR])) {
      $actions[] = [
        'title' => $this->t('Check upload status'),
        'url' => Url::fromRoute('straker_translate.interface_translation.check_upload',
          [
            'component' => $component,
          ],
          ['query' => $this->getDestinationWithQueryArray()]),
        'new_window' => FALSE,
      ];
    }
    if (in_array($source_status, [
      StrakerTranslate::STATUS_EDITED,
      StrakerTranslate::STATUS_UNTRACKED,
      StrakerTranslate::STATUS_ERROR,
      StrakerTranslate::STATUS_CANCELLED,
      StrakerTranslate::STATUS_ARCHIVED,
      StrakerTranslate::STATUS_DELETED,
    ])) {
      if ($doc_id) {
        $actions[] = [
          'title' => $this->t('Update document'),
          'url' => Url::fromRoute('straker_translate.interface_translation.update',
            [
              'component' => $component,
            ],
            ['query' => $this->getDestinationWithQueryArray()]),
          'new_window' => FALSE,
        ];
      }
      else {
        $actions[] = [
          'title' => $this->t('Upload document'),
          'url' => Url::fromRoute('straker_translate.interface_translation.upload',
            [
              'component' => $component,
            ],
            ['query' => $this->getDestinationWithQueryArray()]),
          'new_window' => FALSE,
        ];
      }
    }
    if ($source_status == StrakerTranslate::STATUS_CURRENT || $source_status == StrakerTranslate::STATUS_EDITED) {
      $actions[] = [
        'title' => $this->t('Open in Verify'),
        'url' => Url::fromRoute('straker_translate.workbench', [
          'doc_id' => $doc_id,
        ]),
        'new_window' => TRUE,
      ];
      $actions[] = [
        'title' => $this->t('Re-upload document'),
        'url' => Url::fromRoute('straker_translate.interface_translation.update',
          [
            'component' => $component,
          ],
          ['query' => $this->getDestinationWithQueryArray()]),
        'new_window' => FALSE,
      ];
      if ($doc_id) {
        $actions[] = [
          'title' => $this->t('Re-Check document'),
          'url' => Url::fromRoute('straker_translate.interface_translation.check_upload',
            [
              'component' => $component,
            ],
            ['query' => $this->getDestinationWithQueryArray()]),
          'new_window' => FALSE,
        ];
      }
    }
    return $actions;
  }

  /**
   *
   */
  protected function getSourceActionUrlForUI($component, $source_status) {
    $url = NULL;
    if (in_array($source_status, [StrakerTranslate::STATUS_READY, StrakerTranslate::STATUS_PROCESSING, StrakerTranslate::STATUS_ERROR])) {
      $url = Url::fromRoute('straker_translate.interface_translation.check_upload', [],
        ['query' => ['component' => $component] + $this->getDestinationWithQueryArray()]);
    }
    if (in_array($source_status, [StrakerTranslate::STATUS_EDITED, StrakerTranslate::STATUS_UNTRACKED, StrakerTranslate::STATUS_ERROR, StrakerTranslate::STATUS_CANCELLED, StrakerTranslate::STATUS_ARCHIVED, StrakerTranslate::STATUS_DELETED])) {
      if ($doc_id = \Drupal::service('straker_translate.interface_translation')->getDocumentId($component)) {
        $url = Url::fromRoute('straker_translate.interface_translation.update', [],
          ['query' => ['component' => $component] + $this->getDestinationWithQueryArray()]);
      }
      else {
        $url = Url::fromRoute('straker_translate.interface_translation.upload', [],
          ['query' => ['component' => $component] + $this->getDestinationWithQueryArray()]);
      }
    }
    return $url;
  }

  /**
   * Get the source status label.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity.
   * @param string $source_status
   *   The source status.
   *
   * @return string
   *   The source status human-friendly label.
   */
  protected function getSourceStatusText(ContentEntityInterface $entity, $source_status) {
    switch ($source_status) {
      case StrakerTranslate::STATUS_UNTRACKED:
      case StrakerTranslate::STATUS_REQUEST:
        return t('Upload');

      case StrakerTranslate::STATUS_DISABLED:
        return t('Disabled, cannot request translation');

      case StrakerTranslate::STATUS_READY:
        return $this->t('Project Created, Check Status Pending');

      case StrakerTranslate::STATUS_EDITED:
        return (\Drupal::service('straker_translate.content_translation')->getDocumentId($entity)) ?
          t('Re-upload (content has changed since last upload)') : t('Upload');

      case StrakerTranslate::STATUS_IMPORTING:
        return t('Token payment pending');

      case StrakerTranslate::STATUS_PROCESSING:
        return $this->t('Project created, Translation in progress');

      case StrakerTranslate::STATUS_CURRENT:
        return t('Source Translated');

      case StrakerTranslate::STATUS_ERROR:
        return t('Error');

      case StrakerTranslate::STATUS_CANCELLED:
        return $this->t('Cancelled by user');

      case StrakerTranslate::STATUS_ARCHIVED:
        return $this->t('This document was archived in Straker Translate. Re-upload to translate.');

      case StrakerTranslate::STATUS_DELETED:
        return $this->t('This document was deleted in Straker Translate. Re-upload to translate.');

      default:
        return ucfirst(strtolower($source_status));
    }
  }

  /**
   *
   */
  protected function getSourceStatusTextForUI($component, $source_status) {
    switch ($source_status) {
      case StrakerTranslate::STATUS_UNTRACKED:
      case StrakerTranslate::STATUS_REQUEST:
        return t('Upload');

      case StrakerTranslate::STATUS_DISABLED:
        return t('Disabled, cannot request translation');

      case StrakerTranslate::STATUS_EDITED:
        return (\Drupal::service('straker_translate.interface_translation')->getDocumentId($component)) ?
          t('Re-upload (content has changed since last upload)') : t('Upload');

      case StrakerTranslate::STATUS_READY:
        return $this->t('Project Created, Check Status Pending');

      case StrakerTranslate::STATUS_PROCESSING:
        return $this->t('Project created, Translation in progress');

      case StrakerTranslate::STATUS_CURRENT:
        return t('Source uploaded');

      case StrakerTranslate::STATUS_ERROR:
        return t('Error');

      case StrakerTranslate::STATUS_CANCELLED:
        return $this->t('Cancelled by user');

      case StrakerTranslate::STATUS_ARCHIVED:
        return $this->t('This document was archived in Straker Translate. Re-upload to translate.');

      case StrakerTranslate::STATUS_DELETED:
        return $this->t('This document was deleted in Straker Translate. Re-upload to translate.');

      default:
        return ucfirst(strtolower($source_status));
    }
  }

  /**
   * Get a destination query with the current uri.
   *
   * @return array
   *   A valid query array for the Url construction.
   */
  protected function getDestinationWithQueryArray() {
    return ['destination' => \Drupal::request()->getRequestUri()];
  }

}
