<?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;
    }


    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 ($subcommand !== '') {
            if ($group = $this->findGroupByName(command: $command)) {
                if ($group->exec(subcommand: $subcommand)) {
                    exit(0);
                } else {
                    echo COLOR_DEFAULT . 'Unknown subcommand ' . COLOR_YELLOW . $subcommand . COLOR_DEFAULT .' for ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
                    exit(1);
                }
            } else {
                echo COLOR_DEFAULT . 'Unknown subcommand ' . COLOR_YELLOW . $subcommand . COLOR_DEFAULT .' for ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
                exit(1);
            }
        } else {
            // check for command group and print available commands
            foreach ($this->commandGroups as $group) {
                if ($group->getName() === $command) {
                    echo 'Available subcommands for: ' . COLOR_YELLOW . $group->getName() . COLOR_DEFAULT . ':' . PHP_EOL;
                    $group->printCommands(strlen(string: $group->getName()));
                    exit(0);
                }
            }
        }
        echo COLOR_DEFAULT . 'Unknown command ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
    }
}