<?php

declare(strict_types=1);

namespace Drupal\lms_xapi_lesson\Entity\Handlers;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\lms\Entity\Handlers\LmsLessonHandlerBase;
use Drupal\lms\Entity\LessonStatusInterface;
use Drupal\lms\TrainingManager;
use Drupal\lms_xapi_lesson\Entity\Bundle\XapiLesson;
use Drupal\lms_xapi_lesson\Form\XapiLessonForm;
use Symfony\Component\DependencyInjection\Attribute\AutowireCallable;

/**
 * Xapi lesson handler.
 */
final class XapiLmsLessonHandler extends LmsLessonHandlerBase {

  public function __construct(
    #[AutowireCallable(service: 'entity.form_builder', method: 'getForm')]
    \Closure $getEntityForm,
    #[AutowireCallable(service: 'datetime.time', method: 'getRequestTime')]
    private \Closure $getRequestTime,
    EntityTypeManagerInterface $entityTypeManager,
    TrainingManager $trainingManager,
    protected readonly FormBuilderInterface $formBuilder,
  ) {
    parent::__construct($getEntityForm, $getRequestTime, $entityTypeManager, $trainingManager);
  }

  /**
   * Alter lesson entity form.
   */
  public function alterLessonForm(array &$form, FormStateInterface $form_state): void {
    // We don't have activities on this one, all related fields can be removed.
    unset($form['backwards_navigation']);
    unset($form['randomization']);
    unset($form['random_activities']);
  }

  /**
   * {@inheritdoc}
   */
  protected function setLessonStatusActivities(LessonStatusInterface $lesson_status, ?string $current_activity_delta = NULL): void {
    $lesson_status->setCurrentActivityDelta(0);
  }

  /**
   * {@inheritdoc}
   */
  public function getAnswerForm(LessonStatusInterface $lesson_status): array {
    $build = [];
    $lesson = $lesson_status->getLesson();
    $build['embed'] = $lesson->get(XapiLesson::XAPI_PACKAGE)->view([
      'type' => 'lms_xapi',
      'label' => 'hidden',
    ]);
    $build['form'] = $this->formBuilder->getForm(XapiLessonForm::class, $lesson_status);
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function updateStatus(LessonStatusInterface $lesson_status): bool {
    $lesson_status->setPassPercentage(100)
      ->setEvaluated(TRUE)
      ->setFinished(($this->getRequestTime)())
      ->save();
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function buildResults(array &$element, LessonStatusInterface $lesson_status): void {
    $element['result'] = [
      '#markup' => $this->t('Lesson score: @score%', [
        '@score' => $lesson_status->getScore(),
      ]),
    ];
  }

}
