<?php

declare(strict_types=1);

namespace Drupal\lms_xapi\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\ConfigTarget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\lms_xapi\XapiService;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * LMS Xapi settings form class.
 */
final class LmsXapiSettingsForm extends ConfigFormBase {

  /**
   * The module handler service.
   */
  protected ModuleHandlerInterface $moduleHandler;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return parent::create($container)->injectServices($container);
  }

  /**
   * Inject services to the object.
   */
  public function injectServices(ContainerInterface $container): self {
    $this->moduleHandler = $container->get(ModuleHandlerInterface::class);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'lms_xapi_admin_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [XapiService::CONFIG_NAME];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['endpoint'] = [
      '#type' => 'textfield',
      '#title' => $this->t('LRS API endpoint'),
      '#config_target' => new ConfigTarget(XapiService::CONFIG_NAME, 'endpoint'),
      '#required' => TRUE,
    ];
    if ($this->moduleHandler->moduleExists('lrs_xapi')) {
      $form['endpoint']['#description'] = $this->t('Use "/lrs/endpoint" for internal LRS storage. Make sure username and password match.');
    }
    $form['username'] = [
      '#type' => 'textfield',
      '#title' => $this->t('LRS API user name'),
      '#config_target' => new ConfigTarget(XapiService::CONFIG_NAME, 'username'),
      '#required' => TRUE,
    ];
    $form['password'] = [
      '#type' => 'password',
      '#title' => $this->t('LRS API password'),
      '#config_target' => new ConfigTarget(XapiService::CONFIG_NAME, 'password'),
      '#required' => TRUE,
    ];

    return parent::buildForm($form, $form_state);
  }

}
