<?php

declare(strict_types=1);

namespace Drupal\Tests\netforum\xWeb;

readonly class NetForumXmlSettings implements \JsonSerializable {

  public function __construct(
    public string $xWebUsername,
    public string $xWebPassword,
    public AuthExpirationPolicy $authExpirationPolicy = AuthExpirationPolicy::Absolute,
    public bool $authCredentialsLockedOut = FALSE,
    public array $authFailFunctionList = [],
    public array $authLockFunctionList = [],
    // In seconds, 20 minutes by default.
    public int $authTokenExpiration = 1200,
  ) {}

  public static function fromJsonFile(string $file): NetForumXmlSettings {
    $file = file_get_contents($file);
    if ($file === FALSE) {
      throw new \RuntimeException('Could not read settings file.');
    }

    return static::fromJson($file);
  }

  public static function fromJson(string $json): NetForumXmlSettings {
    $data = json_decode($json, TRUE);

    return new NetForumXmlSettings(
      $data['xWebUsername'], $data['xWebPassword'],
      AuthExpirationPolicy::from($data['authExpirationPolicy']),
      $data['authCredentialsLockedOut'],
      $data['authFailFunctionList'],
      $data['authLockFunctionList'],
      $data['authTokenExpiration'],
    );
  }

  public function toJson(): string {
    $json = json_encode($this);
    if ($json === FALSE) {
      throw new \RuntimeException('Could not encode settings to JSON.');
    }

    return $json;
  }

  public function jsonSerialize(): array {
    return [
      'xWebUsername' => $this->xWebUsername,
      'xWebPassword' => $this->xWebPassword,
      'authExpirationPolicy' => $this->authExpirationPolicy->value,
      'authCredentialsLockedOut' => $this->authCredentialsLockedOut,
      'authFailFunctionList' => $this->authFailFunctionList,
      'authLockFunctionList' => $this->authLockFunctionList,
      'authTokenExpiration' => $this->authTokenExpiration,
    ];
  }

}
