<?php

declare(strict_types=1);

namespace Drupal\siteimprove_accessibility\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\NodeInterface;
use Drupal\siteimprove_accessibility\AlfaScanInterface;
use Drupal\siteimprove_accessibility\Repository\OccurrenceRepository;

/**
 * Defines the AlfaScan entity.
 *
 * @ContentEntityType(
 *   id = "alfa_scan",
 *   label = @Translation("Alfa Scan"),
 *   label_collection = @Translation("Alfa Scans"),
 *   label_singular = @Translation("Alfa Scan"),
 *   label_plural = @Translation("Alfa Scans"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Alfa Scan",
 *     plural = "@count Alfa Scans",
 *   ),
 *   handlers = {
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" =
 *   "Drupal\siteimprove_accessibility\AlfaScanAccessControlHandler",
 *     "form" = {
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "delete-multiple-confirm" =
 *   "Drupal\Core\Entity\Form\DeleteMultipleForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "siteimprove_accessibility_alfa_scan",
 *   admin_permission = "administer alfa_scan",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 *   constraints = {
 *     "UniqueField" = {"nid"},
 *   },
 *   links = {
 *     "collection" = "/admin/content/alfa-scan",
 *     "canonical" = "/alfa-scan/{alfa_scan}",
 *     "delete-form" = "/alfa-scan/{alfa_scan}/delete",
 *     "delete-multiple-form" = "/admin/content/alfa-scan/delete-multiple",
 *   },
 * )
 */
final class AlfaScan extends ContentEntityBase implements AlfaScanInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['nid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Node'))
      ->setDescription(t('The node associated with this scan.'))
      ->setSetting('target_type', 'node')
      ->setRequired(TRUE)
      ->addConstraint('UniqueField')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'entity_reference_label',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['scan_results'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Scan Results'))
      ->setDescription(t('JSON encoded scan results containing evaluation outcomes.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 0)
      ->setDisplayOptions('form', [
        'type' => 'textarea',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string_long',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time the scan was created.'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Updated'))
      ->setDescription(t('The time the scan was last updated.'))
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    $node = $this->get('nid')->entity;

    if ($node instanceof NodeInterface) {
      return $node->getTitle();
    }

    return $this->t('Alfa Scan @id', ['@id' => $this->id()]);
  }

  /**
   * Checks if initial scan has been performed.
   */
  public static function isInitialRun(): bool {
    return (bool) \Drupal::state()->get('siteimprove_accessibility.initial_scan_run', FALSE);
  }

  /**
   * Sets the initial scan run status.
   */
  public static function setInitialRun(bool $status): void {
    \Drupal::state()->set('siteimprove_accessibility.initial_scan_run', $status);
  }

  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageInterface $storage, $update = \NULL) {
    parent::postSave($storage, $update);

    // Sets initial run flag after first item is saved.
    if (!self::isInitialRun()) {
      self::setInitialRun(TRUE);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
    parent::postDelete($storage, $entities);

    $occurrenceRepository = \Drupal::service('siteimprove_accessibility.occurrence_repository');
    if ($occurrenceRepository instanceof OccurrenceRepository) {
      foreach ($entities as $entity) {
        $occurrenceRepository->deleteOccurrences($entity);
      }
    }
  }

}
