<?php

namespace App\Dto\Input;

use ApiPlatform\Metadata\ApiProperty;
use App\Dto\Output\CommandOutput;
use App\Entity\Command;
use App\Entity\CommandGroup;
use phpDocumentor\Reflection\Types\Boolean;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

final class CommandGroupInput
{
    #[Assert\NotBlank(message: 'validators.command_group.name.not_blank')]
    #[Groups(['command-group:write'])]
    #[ApiProperty(
        description: 'El nombre del grupo de comandos',
        example: 'Command Group 1',
    )]
    public ?string $name = null;

    /**
     * @var CommandOutput[]
     */
    #[Groups(['command-group:write'])]
    #[ApiProperty(
        description: 'Los comandos del grupo',
        example: 'Comandos del grupo',
    )]
    public array $commands = [];

    #[Groups(['command-group:write'])]
    #[ApiProperty(
        description: '¿Está habilitado el grupo de comandos?',
        example: 'true',
    )]
    public ?bool $enabled = true;

    public function __construct(?CommandGroup $commandGroup = null)
    {
        if (!$commandGroup) {
            return;
        }

        $this->name = $commandGroup->getName();

        if ($commandGroup->getCommands()) {
            foreach ($commandGroup->getCommands() as $command) {
                $this->commands[] = new CommandOutput($command);
            }
        }

        $this->enabled = $commandGroup->isEnabled();
    }

    public function createOrUpdateEntity(?CommandGroup $commandGroup = null): CommandGroup
    {
        if (!$commandGroup) {
            $commandGroup = new CommandGroup();
        }

        $commandGroup->setName($this->name);

        foreach ($this->commands as $command) {
            $commandsToAdd[] = $command->getEntity();
        }

        $commandGroup->setCommands( $commandsToAdd ?? [] );

        return $commandGroup;
    }
}
