<?php
namespace nur\sery\tools;

use nur\sery\wip\app\app2;
use nur\sery\wip\app\cli\Application;
use nur\sery\wip\app\cli\bg_launcher;
use nur\yaml;

class BgLauncherApp extends Application {
  const ACTION_INFOS = 0, ACTION_START = 1, ACTION_STOP = 2;
  const ARGS = [
    "purpose" => "lancer un script en tâche de fond",
    "usage" => "ApplicationClass args...",

    "sections" => [
      parent::VERBOSITY_SECTION,
    ],

    ["-i", "--infos", "name" => "action", "value" => self::ACTION_INFOS,
      "help" => "Afficher des informations sur la tâche",
    ],
    ["-s", "--start", "name" => "action", "value" => self::ACTION_START,
      "help" => "Démarrer la tâche",
    ],
    ["-k", "--stop", "name" => "action", "value" => self::ACTION_STOP,
      "help" => "Arrêter la tâche",
    ],
  ];

  protected int $action = self::ACTION_START;

  protected ?array $args = null;

  function main() {
    $args = $this->args;

    $appClass = $args[0] ?? null;
    if ($appClass === null) {
      self::die("Vous devez spécifier la classe de l'application");
    }
    $appClass = $args[0] = str_replace("/", "\\", $appClass);
    if (!class_exists($appClass)) {
      self::die("$appClass: classe non trouvée");
    }

    $useRunfile = constant("$appClass::USE_RUNFILE");
    if (!$useRunfile) {
      self::die("Cette application ne supporte le lancement en tâche de fond");
    }

    $runfile = app2::with($appClass)->getRunfile();
    switch ($this->action) {
    case self::ACTION_START:
      $appClass::_manage_runfile(count($args), $args, $runfile);
      array_splice($args, 0, 0, [
        PHP_BINARY,
        NULIB_APP_app_launcher,
      ]);
      app2::params_putenv();
      bg_launcher::_start($args, $runfile);
      break;
    case self::ACTION_STOP:
      bg_launcher::_stop($runfile);
      break;
    case self::ACTION_INFOS:
      yaml::dump($runfile->read());
      break;
    }
  }
}
