<?php

declare(strict_types=1);

namespace Drupal\miniorange_webauthn;

use Drupal;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Url;
use Drupal\miniorange_2fa\MoAuthUtilities;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Provides a list controller for the miniorange webauthn credential entity type.
 */
final class MoWebauthnCredentialListBuilder extends EntityListBuilder {

    public function getOperations(EntityInterface $entity):array
    {
      $newOperations['delete'] = [
        'title' => $this->t('Delete'),
        'weight' => 20,
        'url' => Url::fromRoute('mo_webauthn.remove_configuration', ['id' => $entity->id(), 'user' => Drupal::currentUser()->id()]),
        'attributes' => [
          'class' => ['use-ajax'],
          'data-dialog-type' => 'modal',
        ],
      ];
      $operations = parent::getOperations($entity);
      return $newOperations+$operations;
    }


  /**
   * {@inheritdoc}
   */
  public function buildHeader(): array {
    $web_authn_configured = MoAuthUtilities::isWebAuthnConfiguredForUser(Drupal::currentUser()->id());
    if(!$web_authn_configured){
      $this->messenger()->addWarning($this->t('Please configure Web Authentication as 2FA method for this user first.'));
//      return $form;
    }
    $header['label'] = $this->t('Device');
    $header['status'] = $this->t('Status');
    $header['created'] = $this->t('Created');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity): array {
    $row['label'] = $entity->label();
    $row['status'] = $entity->get('status')->value ? $this->t('Enabled') : $this->t('Disabled');
    $row['created']['data'] = $entity->get('created')->view(['label' => 'hidden']);
    return $row + parent::buildRow($entity);
  }

  public function getEntityIds()
  {
    // Get the user ID from route parameters.
    $user = \Drupal::routeMatch()->getParameter('user');
    $user_id = $user->id();
    $query = $this->getStorage()->getQuery()
      ->accessCheck(TRUE)
      ->sort($this->entityType->getKey('id'));

    // Get the user ID from route parameters.
//    $user_id = \Drupal::routeMatch()->getParameter('user');

    if ($user_id) {
      $query->condition('uid', $user_id);
    }

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query->pager($this->limit);
    }

    return $query->execute();
  }
}
