<?php
namespace nur\ldap;

use nur\A;
use nur\b\ValueException;
use nur\config;
use nur\path;
use nur\sery\output\msg;
use nur\SL;

abstract class ldap_server {
  const NAME = null;

  protected static function name(?string $suffix=null): string {
    $name = static::NAME;
    if ($suffix !== null) {
      $name .= "_";
      $name .= $suffix;
    }
    return $name;
  }

  private static function map_profile(string $profile): string {
    $profile_map = config::k(self::name("profile_map"));
    return A::get($profile_map, $profile, $profile);
  }

  static $profile;

  /** obtenir le profil LDAP courant */
  static function get_profile(): string {
    $profile = self::$profile;
    if ($profile === null) {
      if ($profile === null) $profile = config::k(self::name("profile"));
      if ($profile === null) $profile = self::map_profile(config::get_profile());
      self::$profile = $profile;
    }
    return $profile;
  }

  /** spécifier le profil LDAP courant */
  static function set_profile(?string $profile): void {
    if ($profile === null) $profile = config::get_profile();
    self::$profile = self::map_profile($profile);
  }

  /** adapter le chemin vers le fichier de configuration */
  protected static function fix_path(string $config): string {
    return $config;
  }

  static function conn(?array $config=null, ?string $profile=null): LdapConn {
    if ($profile === null) $profile = self::get_profile();
    $name = self::name();
    msg::debug("Profil $name: $profile");
    $configFile = static::fix_path(ldap_config::get_file($name, $profile));
    if (!file_exists($configFile)) {
      $configname = path::filename($configFile);
      throw new ValueException("$name: profil LDAP invalide (fichier '$configname' non trouvé)");
    }
    return new LdapConn(array_merge(...SL::filter_n([
      require $configFile,
      $config,
    ])));
  }
}