<?php

namespace app;

class CliUtil
{
    protected array $commands = [];

    protected function usage($error = null): never {
        global $argv;

        if (!is_null($error))
            echo "error: {$error}\n\n";

        echo "Usage: $argv[0] COMMAND\n\nCommands:\n";
        foreach ($this->commands as $c => $tmp)
            echo "    $c\n";

        exit(is_null($error) ? 0 : 1);
    }

    public function on(string $command, callable $f) {
        $this->commands[$command] = $f;
        return $this;
    }

    public function run(): void {
        global $argv, $argc;

        if (!isCli())
            CliUtil::die('SAPI != cli');

        if ($argc < 2)
            $this->usage();

        if (empty($this->commands))
            CliUtil::die("no commands added");

        $func = $argv[1];
        if (!isset($this->commands[$func]))
            self::usage('unknown command "'.$func.'"');

        $this->commands[$func]();
    }

    public static function input(string $prompt): string {
        echo $prompt;
        $input = substr(fgets(STDIN), 0, -1);
        return $input;
    }

    public static function silentInput(string $prompt = ''): string {
        echo $prompt;
        system('stty -echo');
        $input = substr(fgets(STDIN), 0, -1);
        system('stty echo');
        echo "\n";
        return $input;
    }

    public static function die($error): never {
        self::error($error);
        exit(1);
    }

    public static function error($error): void {
        fwrite(STDERR, "error: {$error}\n");
    }
}