<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand;

use idoit\Console\IdoitConsoleApplication;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Command\CommandConverter;
use Symfony\Component\Console\Command\Command;

class IdoitCommandConfiguration
{
    public function __construct(
        private IdoitConsoleApplication $cli,
        private CommandConverter $converter,
    )
    {
    }

    public function get(string $name): ?IdoitCommand
    {
        $command = $this->cli->get($name);
        if (!$command) {
            return null;
        }
        return $this->buildConfig($command);
    }

    public function findCommand(string $name): ?Command
    {
        return $this->cli->get($name);
    }

    /**
     * @return IdoitCommand[]
     */
    public function getCommandConfigurations(): array
    {
        $commands = $this->cli->all();

        $configurations = [];
        foreach ($commands as $command) {
            $config = $this->buildConfig($command);

            if ($config) {
                $configurations[$config->getName()] = $config;
            }
        }

        ksort($configurations);

        return array_values($configurations);
    }

    public function buildConfig(Command $command): ?IdoitCommand
    {
        return $this->converter->convert($command);
    }
}