<?php

namespace App\Controller\Commands;

/**
 *
 */
class CommandGroupContainer
{
    private array $commandGroups = [];

    public function addCommandGroup(CommandGroup $commandGroup): CommandGroupContainer
    {
        $this->commandGroups[] = $commandGroup;

        return $this;
    }

    /**
     * @return void
     */
    public function printCommands(): void
    {
        $longestCommandLength = $this->getLongestCommandLength();
        foreach ($this->commandGroups as $commandGroup) {
            $commandGroup->printCommands($longestCommandLength);
        }
    }


    /**
     * @return int
     */
    public function getLongestCommandLength(): int
    {
        $longest = 0;

        foreach ($this->commandGroups as $group) {
            $len = strlen(string: $group->getName());
            if ($len > $longest) {
                $longest = $len;
            }
        }

        return $longest;
    }


    /**
     * @param string $command
     * @return ?CommandGroup
     */
    private function findGroupByName(string $command): ?CommandGroup
    {
        foreach ($this->commandGroups as $group) {
            if ($group->getName() === $command) {
                return $group;
            }
        }
        return null;
    }


    public function run(string $command, string $subcommand): void
    {
        if ($group = $this->findGroupByName(command: $command)) {
            $group->exec(subcommand: $subcommand);
        } else {
            echo COLOR_DEFAULT . 'Unknown command ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
            exit(1);
        }
    }
}