<?php
namespace nur;

use nur\b\authnz\AuthzManager;
use nur\b\authnz\IAuthzUser;

/**
 * Class authz: gestion de l'autorisation
 */
class authz {
  const MANAGER_CLASS = AuthzManager::class;

  protected static $manager_class;

  /**
   * spécifier la classe à utiliser pour instancier le gestionnaire
   * d'autorisation
   *
   * cette méthode *doit* être appelée avant d'appeler la méthode
   * {@link manager()}
   */
  static final function set_manager_class(string $manager_class) {
    self::$manager_class = $manager_class;
  }

  /** @var AuthzManager */
  protected static $manager;

  static final function set_manager(AuthzManager $manager) {
    self::$manager = $manager;
  }

  /** obtenir l'instance globale du gestionnaire d'autorisation */
  static final function manager(): AuthzManager {
    if (self::$manager === null) {
      $manager_class = self::$manager_class;
      if ($manager_class === null) $manager_class = static::MANAGER_CLASS;
      self::$manager = new $manager_class();
    }
    return self::$manager;
  }

  static final function __callStatic($name, $args) {
    $name = str::us2camel($name);
    return call_user_func_array([self::manager(), $name], $args);
  }

  #############################################################################

  const NONE = AuthzManager::STATUS_NONE;
  const INITIAL = AuthzManager::STATUS_INITIAL;
  const DISCONNECTED = AuthzManager::STATUS_DISCONNECTED;
  const UNAUTHORIZED = AuthzManager::STATUS_UNAUTHORIZED;

  static final function get_status(): int { return self::manager()->getStatus(); }
  static final function is_auth(): bool { return self::manager()->isAuth(); }
  static final function is_sulogin(): bool { return self::manager()->isSulogin(); }
  static final function get_auth(): string { return self::manager()->getAuth(); }
  static final function get(): IAuthzUser { return self::manager()->getUser(); }

  static final function is_root(): bool { return self::get()->isPerm("*"); }
  static final function is_admin(): bool { return self::get()->isPerm("admin"); }
}
