<?php
namespace nur\sery\output;

use nur\sery\output\std\ProxyMessenger;
use nur\sery\php\nur_func;

/**
 * Class msg: inscrire un message dans les logs ET l'afficher à l'utilisateur
 *
 * Cette classe DOIT être initialisée avec {@link set_messenger()} ou
 * {@link set_messenger_class()} avant d'être utilisée.
 */
class msg extends _messenger {
  private static ?IMessenger $msg = null;

  private static bool $setup = false;

  static function is_setup(): bool {
    return self::$setup;
  }

  static function set_messenger(IMessenger $msg) {
    self::$msg = $msg;
    self::$setup = true;
  }

  static function get(): IMessenger {
    return self::$msg ??= new ProxyMessenger();
  }

  /**
   * initialiser les instances say, console, log. 
   */
  static function init(array $msgs) {
    $say = $msgs["say"] ?? null;
    $console = $msgs["console"] ?? null;
    $log = $msgs["log"] ?? null;
    $msgs = [];
    if ($log !== null && $log !== false) {
      if ($log instanceof IMessenger) log::set_messenger($log);
      elseif (is_string($log)) log::set_messenger_class($log);
      elseif (is_array($log)) {
        nur_func::ensure_class($log, $args);
        $log = nur_func::cons($log, $args);
      }
      log::set_messenger($log);
      $msgs[] = $log;
    }
    if ($console !== null && $console !== false) {
      if ($console instanceof IMessenger) console::set_messenger($console);
      elseif (is_string($console)) console::set_messenger_class($console);
      elseif (is_array($console)) {
        nur_func::ensure_class($console, $args);
        $console = nur_func::cons($console, $args);
      }
      console::set_messenger($console);
      $msgs[] = $console;
    }
    if ($say !== null && $say !== false) {
      if ($say instanceof IMessenger) say::set_messenger($say);
      elseif (is_string($say)) say::set_messenger_class($say);
      elseif (is_array($say)) {
        nur_func::ensure_class($say, $args);
        $say = nur_func::cons($say, $args);
      }
      say::set_messenger($say);
      $msgs[] = $say;
    }
    if ($say === null && $console !== null) {
      say::set_messenger($console);
    } elseif ($console === null && $say !== null) {
      console::set_messenger($say);
    }
    self::set_messenger(new ProxyMessenger(...$msgs));
  }
}
