<?php

namespace App\Controller\Commands;

/**
 *
 */
class CommandGroup
{
    private array $commands = [];

    public function __construct(private readonly string $name, private readonly string $description)
    {
        // no body
    }


    public function addCommand(Command $command): ?CommandGroup
    {
        $this->commands[] = $command;

        return $this;
    }


    public function getName(): string
    {
        return $this->name;
    }


    public function printCommands(int $longestCommandLength): void
    {
        echo COLOR_YELLOW . str_pad(string: $this->name, length: $longestCommandLength + 1) . COLOR_WHITE . $this->description . COLOR_DEFAULT . PHP_EOL;
        foreach ($this->commands as $command) {
            echo COLOR_GREEN . str_pad(string: ' ', length: $longestCommandLength + 1, pad_type: STR_PAD_LEFT) . $this->name . ':' . $command->getName();
            foreach ($command->getMandatoryParameters() as $optionals) {
                echo ' <' . $optionals . '>';
            }
            foreach ($command->getOptionalParameters() as $mandatory) {
                echo ' {' . $mandatory . '}';
            }
            echo COLOR_WHITE . ' ' . $command->getDescription();
            echo COLOR_DEFAULT . PHP_EOL;
        }
    }

    public function findCommandByName(string $command): ?Command
    {
        foreach ($this->commands as $currentCommand) {
            if ($command === $currentCommand->getName()) {
                return $currentCommand;
            }
        }
        return null;
    }

    private function findCommandGroupByName(string $command)
    {
        echo 'in check';
        foreach ($this->commands as $currentCommand) {
            print_r($currentCommand->getName());
            if ($currentCommand instanceof CommandGroup) {
                if ($command === $currentCommand->getName()) {
                    return $currentCommand;
                }
            }
        }
        return false;
    }

    public function exec(string $subcommand): bool
    {
        if ($command = $this->findCommandByName(command: $subcommand)) {
            $command->exec();
            return true;
        } else {
            return false;
        }
    }

}