<?php

declare(strict_types=1);

namespace ProPresenter\Parser;

use Rv\Data\Action\Label as LabelProto;

/**
 * Wraps a protobuf {@see LabelProto} from the global ProPresenter `Labels`
 * file. Surfaces the label's display name (the protobuf `text` field) and an
 * optional color used by the UI to tint slides / cues that carry the label.
 *
 * Labels do not have a UUID — identity is the name string.
 */
class Label
{
    public function __construct(
        private readonly LabelProto $label,
    ) {
    }

    /**
     * Display name (the protobuf `text` field; this is what the
     * ProPresenter UI renders next to the swatch).
     */
    public function getName(): string
    {
        return $this->label->getText();
    }

    /**
     * Whether the label carries an explicit color message (the absence of a
     * color is not the same as black: ProPresenter renders unset labels with
     * the default UI color).
     */
    public function hasColor(): bool
    {
        return $this->label->hasColor();
    }

    /**
     * Get the label's color as an associative array, or null when unset.
     *
     * Channels are floats in the 0..1 range as stored by ProPresenter.
     *
     * @return array{r: float, g: float, b: float, a: float}|null
     */
    public function getColor(): ?array
    {
        if (!$this->label->hasColor()) {
            return null;
        }

        $color = $this->label->getColor();

        return [
            'r' => $color->getRed(),
            'g' => $color->getGreen(),
            'b' => $color->getBlue(),
            'a' => $color->getAlpha(),
        ];
    }

    /**
     * Convenience: render the color as a 6-digit `#RRGGBB` hex string,
     * dropping alpha. Returns null when the label has no color.
     */
    public function getColorHex(): ?string
    {
        $color = $this->getColor();
        if ($color === null) {
            return null;
        }

        return sprintf(
            '#%02X%02X%02X',
            (int) round(max(0.0, min(1.0, $color['r'])) * 255),
            (int) round(max(0.0, min(1.0, $color['g'])) * 255),
            (int) round(max(0.0, min(1.0, $color['b'])) * 255),
        );
    }

    /**
     * Get the underlying protobuf Label message.
     */
    public function getProto(): LabelProto
    {
        return $this->label;
    }
}
