<?php declare(strict_types = 1);

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

use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Argument\ArgumentConverter;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\IdoitCommand;
use idoit\Module\SyneticsFlows\Automation\Action\ActionType\IdoitCommand\Option\OptionConverter;
use Symfony\Component\Console\Command\Command;

class BuilderConverter implements CommandConverter
{
    public function __construct(
        private OptionConverter $optionConverter,
        private ArgumentConverter $argumentConverter,
        private OrderConverter $optionsOrderConverter,
    )
    {
    }

    public function convert(Command $command): ?IdoitCommand
    {
        $arguments = [];

        foreach ($command->getDefinition()->getArguments() as $argument) {
            $converted = $this->argumentConverter->convert($command, $argument);
            if ($converted) {
                $arguments[] = $converted;
            }
        }

        $options = [];

        foreach ($command->getDefinition()->getOptions() as $option) {
            $converted = $this->optionConverter->convert($command, $option);
            if ($converted) {
                $options[] = $converted;
            }
        }

        if ($this->optionsOrderConverter->supports($command->getName())) {
            $options = $this->optionsOrderConverter->convert($command->getName(), $options);
        }

        return new IdoitCommand($command->getName(), $command->getDescription(), $options, $arguments);
    }

    public function supports(Command $command): bool
    {
        return true;
    }
}